2017-09-07 17 views
0

我正在使用C#並以編程方式將複選框添加到Windows窗體。我正在嘗試爲每個創建的複選框分配一個checkedChanged事件處理程序。有沒有辦法在下面的case語句中使用可變的複選框名稱?試圖分配帶變量的checkedChanged事件處理程序複選框名稱

CheckBox chkBox = new CheckBox(); 
chkBox.Location = new System.Drawing.Point(550, y2); 
chkBox.Name = "CheckBox" + optno.ToString(); 
chkBox.Font = new Font("Arial", 10, FontStyle.Bold); 
switch (optno) 
{ 
    case 1: 
     chkBox.Click += new System.EventHandler(this.**CheckBox1**_CheckedChanged); 
     break; 
    case 2: 
     chkBox.Click += new System.EventHandler(this.CheckBox2_CheckedChanged); 
     break; 
    case 3: 
     chkBox.Click += new System.EventHandler(this.CheckBox3_CheckedChanged); 
     break; 

我想避免一長串案件。

+0

你或許應該結合您的處理程序。或者製作一批代表。 – SLaks

+0

處理程序方法有多不同,真的嗎? –

+0

看看https://stackoverflow.com/questions/33107026/dynamic-switch-cases – Tcraft

回答

0
CheckBox chkBox = new CheckBox(); 
chkBox.Location = new System.Drawing.Point(550, y2); 
chkBox.Name = "CheckBox" + optno.ToString(); 
chkBox.Font = new Font("Arial", 10, FontStyle.Bold); 
chkBox.Click += new System.EventHandler(this.CheckBox_CheckedChanged); 

然後,處理程序是:

private void CheckBox_CheckedChanged(object sender, EventArgs e) 
{ 
    CheckBox cb = sender as CheckBox; 
    if (cb != null) 
    { 
    switch (cb.Name) 
    { 
     // a case statement for each combobox control... 
     case "ComboboxOne": 
     // call custom method for handling this checkbox's change 
     DoComboboxOneStuff(); 
     break; 
     case "ComboboxTwo": 
     // call custom method for handling this checkbox's change 
     DoComboboxTwoStuff(); 
     break; 
    } 
    } 
} 

private void DoComboboxOneStuff() 
{ // do your stuff here..} 

private void DoComboboxTwoStuff() 
{ // do your stuff here..} 
+1

'switch(cb.Name)''''''''''''''''''''''''''''''''''''''''''\我至少會在他們的'Tag'屬性中加入一個枚舉。 –

相關問題