gpt4 book ai didi

c# - 如何访问 Windows 窗体中动态创建的复选框

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:08 25 4
gpt4 key购买 nike

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!!!");
}

关于c# - 如何访问 Windows 窗体中动态创建的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com