单击带有附加参数的按钮集的事件处理程序

Click event handler for set of buttons with additional argurment

这是我创建按钮并为其附加事件的代码。

 for (int i = 0; i < NumberOfQuestion; i++)
     {
                Telerik.WinControls.UI.RadButton button = new Telerik.WinControls.UI.RadButton();
                // radButton1
                // 
                button.Anchor = AnchorStyles.None;
                button.Font = new Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Bold);
                button.Location = new Point(65 * i + 15, 10);
                button.Name = "btn_cauhoi" + (i + 1);
                button.Size = new Size(60, 35);
                button.TabIndex = 1 + i;
                button.Text = "Câu " + (i + 1);

                button.Click += (sender, e) => Button_Click(sender, e, (i + 1));

                // 

                panel_nut_cauhoi.Controls.Add(button);
      }


 private void Button_Click(object sender, EventArgs e, int questionIndex)
 {
        MessageBox.Show(questionIndex.ToString());
 }

当我点击每个按钮时它只显示 questionIndex = the lastIndex + 1

请有人帮帮我!

您不需要也不能向事件处理程序传递额外的参数。要使用索引,您可以使用以下任一选项:

选项 1 -(首选)封装您想要在点击时执行的逻辑,在 DoSomething 方法中 void DoSomething(int index) 并分配事件以这种方式处理按钮:

var j = i + 1;
button.Click += (obj, ea) => {DoSomething(j);};
//If for any reason you want to call your `Button_Click`, you can do it this way:
//button.Click += (sender, e) => Button_Click(sender, e, (i + 1));

选项 2 - 将索引设置为 ButtonTag 属性,然后在事件处理程序中将发送者转换为 Button 并从 Tag 属性:

中拆箱索引
var button = (RadButton)sender;
var index = (int) button.Tag;

选项 3 - 将按钮存储在 List<RadButton> 中,并在事件处理程序中找到列表中的发件人索引:

var button = (RadButton)sender;
var index = list.IndexOf(button);