【问题标题】:Click event for a Button Array按钮数组的单击事件
【发布时间】:2013-11-01 18:20:07
【问题描述】:

我在 C# WFA 中有一个 Button 数组,我想为单击数组中的任何按钮创建一个事件。 我该怎么做? 以及如何知道它在数组中的哪个位置? 我知道发件人就是按钮本身

【问题讨论】:

    标签: c# windows winforms button


    【解决方案1】:

    您可以使用for 循环来关闭包含当前索引的变量:

    for(int i = 0; i < buttons.Length; i++)
    {
        //it's important to have this; closing over the loop variable would be bad
        int index = i;  
        buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
    }
    

    【讨论】:

    • 谢谢。我只想知道,最后一行是什么?我知道它在做什么,只是想知道它是怎么叫的,这样我就可以学习它了。
    • 它正在创建一个匿名方法;这种特殊的语法称为 lambda 表达式。
    【解决方案2】:

    您可以将事件处理程序添加到 for 循环中的每个按钮。

    在处理程序内部,您可以调用array.IndexOf((Button)sender)

    【讨论】:

      【解决方案3】:

      试试这个

      namespace WindowsFormsApplication1
      {
          public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
      
              Button[] myButtons = new Button[10];
              private void Form1_Load(object sender, EventArgs e)
              {
      
                  for(int i = 0; i < myButtons.Length; i++)
                  {
                      int index = i;
                      this.myButtons[i] = new Button();
      
                      this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
                      this.myButtons[i].Name = "button" + (index + 1);
                      this.myButtons[i].Size = new System.Drawing.Size(70, 23);
                      this.myButtons[i].TabIndex = i;
                      this.myButtons[i].Text = "button" + (index + 1);
                      this.myButtons[i].UseVisualStyleBackColor = true;
                      this.myButtons[i].Visible = true;
      
                      myButtons[i].Click += (sender1, ex) => this.Display(index+1);
      
                      this.Controls.Add(myButtons[i]);
                  }
              }
      
              public void Display(int i)
              {
                  MessageBox.Show("Button No " + i);
              }
      
          }
      }
      

      【讨论】:

      • 这不会编译。 Display 的语法不正确,您是在 for 循环中调用该方法,而不是从中创建委托。
      • 如何将图像添加到按钮此方法对我有用,我现在正在尝试添加图像
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      相关资源
      最近更新 更多