一个选项是List<CheckBox>
在类级别创建一个来保存您创建的复选框的集合。
例子:
List<CheckBox> CheckBoxes = new List<CheckBox>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CreateCheckBoxes();
}
private void CreateCheckBoxes()
{
//Create 3 checkboxes
int intialTop = 50;
for (int i = 0; i < 3; i++)
{
CheckBox chk = new CheckBox();
chk.Top = intialTop;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest";
this.Controls.Add(chk);
CheckBoxes.Add(chk);
intialTop += 20;
}
//You can access your checkboxes anywhere in Form1 now.
var first = CheckBoxes.First();
first.Text = "First Checkbox";
}
附加示例:
此示例显示向表单添加两个复选框以及为它们提供自己的单击事件处理程序。
CheckBox checkBoxA;
CheckBox checkBoxB;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Add checkbox A
checkBoxA = new CheckBox();
checkBoxA.Top = 10;
checkBoxA.Left = 50;
checkBoxA.Text = "CheckBoxA";
//Register the event handler for this checkbox
checkBoxA.Click += new EventHandler(checkBoxA_Click);
this.Controls.Add(checkBoxA);
//Add checkbox B
checkBoxB = new CheckBox();
checkBoxB.Top = 30;
checkBoxB.Left = 50;
checkBoxB.Text = "checkBoxB";
//Register the event handler for this checkbox
checkBoxB.Click += new EventHandler(checkBoxB_Click);
this.Controls.Add(checkBoxB);
}
void checkBoxA_Click(object sender, EventArgs e)
{
MessageBox.Show("CheckBoxA has been clicked!!!");
}
void checkBoxB_Click(object sender, EventArgs e)
{
MessageBox.Show("CheckBoxB has been clicked!!!");
}