c# - 动态创建复选框并检测已选中

标签 c# checkbox

我正在 GroupBox 内使用 for 循环动态创建五个复选框。 现在,它们是动态创建的,所以我不知道如何为它们附加一个 ChangeCheck 方法?

所有这些复选框都是相关的,所以我想做的是这样的:

  1. 动态创建 5 个复选框
  2. 将每个复选框添加到列表中
  3. 当列表中的特定复选框打开时触发方法。

这就是我创建复选框的方式:

for (int i = 0; i < 5; i++)
{
    CheckBox chk = new CheckBox();
    chk.size = new Size(10, 10);
    chk.Top = 10
    chk.Left = 20
    chk.Text = i.ToString();
    group_box_name.controls.Add(chk);
}

现在,我如何检测哪个复选框处于打开/关闭状态?

最佳答案

您可以执行以下操作:

int top = 0;
for (int i = 0; i < 5; i++)
{
   CheckBox chk = new CheckBox();
   chk.size = new Size(10, 10);
   chk.Top += (5 + 10); //Spacing = 5, CheckboxHeight = 10
   chk.Left = 20;
   chk.Text = i.ToString();
   chk.CheckedChanged += CheckBox_CheckedChanged;
   chk.Tag = i;/*You can put anything here. 
                 Otherwise you could also use the Name property.. 
                 It just helps to determine which checkbox was currently checked */    
   group_box_name.controls.Add(chk);
}

private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
   CheckBox cbx = (CheckBox)sender;
   if(cbx != null)
   {
      int tag = int.Parse(cbx.Tag.ToString());
      switch(tag)
      {
         case 0:
         //Do whatever:
         break;

         //Handle other cases here:
      }
   }
}

关于c# - 动态创建复选框并检测已选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39099058/

相关文章:

html - 在 Angular2 中选中复选框时启动事件

ios - 当我选中一个复选框时,所有复选框都被选中(Swift)

php - 在 MySQL 中存储第二个复选框的值

asp.net - 带有 jquery 的 IE 复选框无法正常工作

c# - N阶贝塞尔曲线

c# - 设置为透明时控件中的黑色背景色

c# - WebAPI 中的应用程序服务代码

java - 如何改变android复选框按钮的大小?

c# - WPF 中 RichTextBox 内的光标位置

c# - 稳步减慢从 javascript 到 WCF 服务的 ajax 调用