2016-12-24 22 views
1

这是我创建按钮和附加事件给他们的代码。单击事件处理程序的一组按钮与额外的参数

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 =的lastIndex的+ 1当我点击每个按钮

有人帮助我,好吗!

回答

2

您不需要也不能将其他参数传递给事件处理程序。使用索引,您可以使用这些选项:

选项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属性,然后在事件处理程序投发件人ButtonTag财产拆箱指数:

var button = (RadButton)sender; 
var index = (int) button.Tag; 

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

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

选项1不工作 –

+0

检查编辑。纠正。 –

+0

我又遇到了一个问题。你能帮我吗 ? http://stackoverflow.com/questions/41311043/button-trigger-event-gotfocus-repeattly –

相关问题