C# 为 form 窗体中的所有相同组件循环添加相同事件,这样减少了代码量。

private void Form2_Load(object sender, EventArgs e)
        {
            foreach (Control c in groupBox1.Controls)//遍历groupBox1内的所有控件
            {
                if (c is CheckBox)//只遍历CheckBox控件
                {
                    ((CheckBox)c).CheckStateChanged += new EventHandler(chk_CheckedChanged);
                }
            }
 
        }
 
        private void chk_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).CheckState.ToString() == "Checked")
            {
                listBox1.Items.Add(((CheckBox)sender).Text);
            }
            else
            {
                listBox1.Items.Remove(((CheckBox)sender).Text);
            }
        }

 

相关文章:

  • 2021-11-09
  • 2022-12-23
  • 2021-12-20
  • 2021-07-14
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-27
  • 2022-03-07
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
相关资源
相似解决方案