我正在使用C#并以编程方式向Windows窗体添加复选框。我正在尝试为每个创建的复选框分配一个checkedChanged事件处理程序。有没有办法在以下case语句中使用可变量复选框名称?
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 :(得分: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..}