【问题标题】:trying to assign a checkedChanged event handler with variable Checkbox name尝试分配带有变量 Checkbox 名称的 checkedChanged 事件处理程序
【发布时间】:2023-03-28 01:30:01
【问题描述】:

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

我想避免一长串案例。

【问题讨论】:

标签: c# checkbox


【解决方案1】:
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..}

【讨论】:

  • switch (cb.Name) 一定会在几次修改之后以眼泪收场。我至少会在他们的 Tag 属性或其他东西中放置一个枚举。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多