【问题标题】:c# how to deal with events for multi dynamic created buttonsc#如何处理多动态创建按钮的事件
【发布时间】:2010-09-05 09:48:42
【问题描述】:

我创建了一个 WinForm 并添加了动态按钮,我如何处理它的事件

public static void Notify()
{

    var line = 3;

    Form fm = new Form();
    fm.Text = "Hello!";
    fm.ShowInTaskbar = false;
    fm.ShowIcon = false;
    fm.MinimizeBox = false;
    fm.MaximizeBox = false;
    fm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
    fm.TopMost = true;
    fm.ClientSize = new Size(150, 75 * line/2);
    Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
    int left = workingArea.Width - fm.Width-5;
    int top = workingArea.Height - fm.Height-4;
    fm.Location = new Point(left, top);
    fm.StartPosition = FormStartPosition.Manual;

    var buttomArray = new Button[line];

    for (int i = 0; i < line; i++)
    {
        buttomArray[i] = new Button();
        buttomArray[i].Text = "Button " + (i + 1);
        buttomArray[i].Location = new Point(10,30*(i+1) - 16);
        buttomArray[i].Size = new Size(130,25);
        fm.Controls.AddRange(new Control[] { buttomArray[i] });
    }

    fm.Show();
}

当我点击不同的按钮时,我希望能够做一些不同的事情(也许我可以使用“名称”作为标识符?)

干杯

【问题讨论】:

    标签: c# winforms events button handler


    【解决方案1】:

    只需分配Click 处理程序:

    for (int i = 0; i < 10; i++)
    {
        var btn = new Button();
        btn.Text = "Button " + i;
        btn.Location = new Point(10, 30 * (i + 1) - 16);
        btn.Click += (sender, args) =>
        {
            // sender is the instance of the button that was clicked
            MessageBox.Show(((Button)sender).Text + " was clicked");
        };
        Controls.Add(btn);
    }
    

    【讨论】:

      【解决方案2】:

      订阅 Button.Click 事件。当您处于创建循环中时,将您要在点击处理程序中使用的数据附加到 Tag-property。

      for (int i = 0; i < line; i++) 
          { 
              buttomArray[i] = new Button(); 
              buttomArray[i].Tag=i;
          .....
      

      在点击处理程序中,发送者将是按钮(您可以强制转换为它),并且标签将包含您的值。

      Button btn=(Button)sender;
      int value=(int)btn.Tag;
      

      标签属性接受任何类型。因此,您可以为其附加任何值。

      【讨论】:

      • 谢谢 Tag 属性一定会很方便:-)
      • @Data-Base:这取决于您的代码的构建方式。使用标签属性更老派。如果您习惯于为每个事件声明事件处理程序方法,那么这是要走的路。内联方式更加优雅和高效,但并不适合所有人。除此之外,如果使用不当,还会导致代码不可读。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2017-07-29
      • 1970-01-01
      • 2015-03-02
      • 2012-02-03
      • 1970-01-01
      • 2012-08-17
      相关资源
      最近更新 更多