簡體   English   中英

嘗試分配具有可變復選框名稱的checkedChanged事件處理程序

[英]trying to assign a checkedChanged event handler with variable Checkbox name

我正在使用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;

我想避免一堆案件。

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..}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM