动态创建复选框并检测复选框
本文关键字:复选框 检测 动态 创建 | 更新日期: 2023-09-27 18:03:30
我正在GroupBox内动态创建五个复选框,并使用for循环。现在,它们是动态创建的,所以我不知道如何将ChangeCheck方法附加到它们上?
所有这些复选框都是相关的所以我要做的是这样的:
- 动态创建5个复选框
- 将每个复选框添加到列表
- 当列表中的特定复选框处于on状态时触发方法。
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:
}
}
}
将选中的更改事件添加到动态创建的复选框中。您还可以添加名称
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.Name = "chk" + i.ToString();
chk.size = new Size(10, 10);
chk.Top = 10
chk.Left = 20
chk.Text = i.ToString();
chk.CheckedChanged += checkBox_CheckedChanged;
group_box_name.controls.Add(chk);
}
private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
CheckBox chk=sender as CheckBox;
if(chk!=null)
{
if(chk.Checked)
{
string chkName=chk.Name;
string chkText=chk.Text;
//your code
}
}
}