2016-12-24 21 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 –

相關問題