如何访问 Windows 窗体中动态创建的复选框
本文关键字:动态 创建 复选框 窗体 Windows 何访问 访问 | 更新日期: 2023-09-27 18:31:24
form_load
我创建了三个复选框。然后,对于button_click
事件,我想检查复选框的状态,但它们在我的if
语句中不可用。我找到了这段代码作为示例:
CheckBox chk = new CheckBox();
chk.Top = 50;
chk.Left = 50;
chk.Text = "Check Box Test";
chk.Name = "chkTest";
this.Controls.Add(chk);
CheckBox chkTest = (CheckBox)Controls["chkTest"];
仅当我检查form_load
内部的状态时才有效. 如何使用button_click访问复选框?
一种选择是在类级别创建一个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!!!");
}
如前所述,您可以创建一个类级别复选框,然后在代码中需要的任何位置进行检查:
CheckBox checkBox1 = new CheckBox();
private void Form1_Load()
{
checkBox1.Name = "CheckBox1";
checkBox1.Text = "Click Me!";
checkBox1.Click += new EventHandler(checkBox1_Click); // Only need this if you want a click handler
this.Controls.Add(checkBox1);
}
private void checkBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("You click the check box");
}
private void submitButton_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
MessageBox.Show("Check box is checked!");
}
}
或者,您可以循环访问窗体的控件并在此处搜索复选框:
private void CheckCheckBoxes(string checkBoxName)
{
// this.Controls is a collection of all controls on the form (assuming this is run on the Form class)
foreach(Control control in this.Controls)
{
if (control.Name == checkBoxName && control is CheckBox)
{
CheckBox checkBox = control as CheckBox;
if (checkBox.Checked)
{
MessageBox.Show("Check box is checked");
}
}
}
}