Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中动态创建的按钮中使用其名称选择按钮_C#_Winforms_Button - Fatal编程技术网

C# 在c中动态创建的按钮中使用其名称选择按钮

C# 在c中动态创建的按钮中使用其名称选择按钮,c#,winforms,button,C#,Winforms,Button,我正在动态创建按钮。在下面的代码中,如何使用代码剩余部分中的I选择一个特定的按钮,并使用其名称ex: for(int i = 0; i < 5; i++) { button b = new button(); b.name = i.ToString(); } 首先,仅仅创建按钮是不够的。您需要将它们添加到某些控件中: for(int i = 0; i < 5; i++) { Button button = new Button(); button.N

我正在动态创建按钮。在下面的代码中,如何使用代码剩余部分中的I选择一个特定的按钮,并使用其名称ex:

for(int i = 0; i < 5; i++)
{
    button b = new button();
    b.name = i.ToString();
}

首先,仅仅创建按钮是不够的。您需要将它们添加到某些控件中:

for(int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Name = String.Format("button{0}", i); // use better names
    // subscribe to Click event otherwise button is useless
    button.Click = Button_Click;
    Controls.Add(button); // add to form's controls
}

您可以将它们放在按钮[]中,也可以迭代表单的控件集合。

更简单的解决方案是在控件集合中搜索按钮

Button btn = (Button) this.Controls["nameButton"];
//...DO Something
这个解决方案的问题是,如果没有带有nameButton的按钮,JIT将抛出一个异常。如果你想防止这种情况发生,你必须在try-catch块中插入代码,或者,如果你愿意,你可以使用Sergey Berezovskiy解决方案。他使用Linq,我认为更清楚的是,你必须将按钮放在某个地方:


迭代所有控件,键入指定名称的按钮?@TimSchmelter,抱歉。我只是在练习,这就是为什么我对命名约定不太认真的原因。非常感谢您的建议。您还可以将按钮的名称绑定到按钮的命令参数,以便在所有按钮都使用相同的处理程序时,dynamicButton_Click。。。例如,您可以通过检查传递给处理程序的参数来查找单击了哪个按钮。@mikeofst是的,agree-事件发送者很容易在事件处理程序中检索到。我可能会用这些信息更新答案
private void Button_Click(object sender, EventArgs e)
{
    // that's the button which was clicked
    Button button = (Button)sender;
    // use it
}
Button btn = (Button) this.Controls["nameButton"];
//...DO Something
  for (int i = 0; i < 5; i++) {
    // Mind the case: Button, not button
    Button b = new Button();
    // // Mind the case: Name, not name
    b.Name = i.ToString();

    //TODO: place your buttons somewhere:
    // on a panel
    //   myPanel.Controls.Add(b);
    // on a form
    //   this.Controls.Add(b);
    // etc.

    //TODO: it seems, that you want to add Click event, something like
    //  b.Click += MyButtonClick;  
  }
  Button b = myPanel.Controls["1"] as Button;

  if (b != null) {
    // The Button is found ...
  }