C#中如何处理多动态创建的按钮事件

问题描述:

我创建了一个WinForm的,我加入到它的动态按钮,我该怎么处理这事件C#中如何处理多动态创建的按钮事件

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(); 
} 

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

欢呼

简单地分配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); 
} 
+0

感谢完美:-) – 2010-09-05 10:55:01

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

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

在点击处理程序中,发件人将是Button(您可以转换为它)并且标记将包含您的值。

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

标签属性接受任何类型。因此您可以附加任何值。你工作

+0

谢谢Tag属性一定会得心应手:-) – 2010-09-05 10:57:45

+0

@资料库:这取决于你的代码的构建方式。使用Tag-propety更老式。如果您习惯于为每个事件声明eventhandler方法,这就是要走的路。内联的方式更优雅,更高效,但不适合每个人都喜欢。除此之外,如果使用不当,代码将无法读取。 – HCL 2010-09-05 11:29:30