c# - 如何在运行时在框架或面板上添加按钮控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1428504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:26:01  来源:igfitidea点击:

How add button control on frame or panel at runtime in c#

c#winforms

提问by mangesh

windows form application I want desine keypad like pda device .I want all numeric keys in one group therfore I want to arrange all these button on one frame or panel . second frame or panel which contain all the special function keys . I want design this keyboard at runtime after reading xml file description of keypad. please guide me to implement this.

windows 窗体应用程序我想要像 pda 设备一样的设计键盘。我想要一组中的所有数字键,因此我想将所有这些按钮排列在一个框架或面板上。包含所有特殊功能键的第二个框架或面板。我想在阅读键盘的 xml 文件描述后在运行时设计这个键盘。请指导我实现这一点。

回答by Fredrik M?rk

Short version of adding a control to a container (Buttonused as example):

向容器添加控件的简短版本(Button用作示例):

   Button myButton = new Button();
   myButton.Text = "some text";
   // attach event handler for Click event 
   // (assuming ButtonClickHandler is an existing method in the class)
   myButton.Click += ButtonClickHandler;
   myPanel.Controls.Add(myButton);
   // additional code for setting location and such for myButton

The tricky part will probably not be to create the controls and add them to the container, but to arrange them so that it looks good.

棘手的部分可能不是创建控件并将它们添加到容器中,而是排列它们以使其看起来不错。

回答by Ramgy Borja

another example add 5 button

另一个例子添加 5 按钮

    int xlocation = 5;
    for (int i = 1; i <= 5; i++)
    {
         Button newButton = new Button();
         {
             newButton.Name = string.Format("Button{0}", i);
             newButton.Text = string.Format("Button {0}",i);
             newButton.Location = new System.Drawing.Point(xlocation, 10);
             newButton.Size = new System.Drawing.Size(75, 35);
             newButton.Click += btn_msg;
             this.Controls.Add(newButton);
         }
         xlocation = xlocation + 85;
    }

button click Event

按钮点击事件

    public void btn_msg(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        conn.msgErr(btn.Name.ToString());
    }