如何访问像CheckBox或textBox这样的Group Box项? [英] How do I access a Group Box item like a checkBox or textBox?
问题描述
这就是我在form1上的内容:
checkBox0 ... to checkBox9 ==>在GroupBoxA
textBox0 ...到textBox9 ==>在GroupBoxB
richTextBox1
我想访问每个Box in一个循环。像这样
for(int i = 0; i< = 9; i ++){
richTextBox .AppendText(checkBox [i] + textBox [i]);
}
这个问题没什么意义。具体如何与群组相关?
如果你想访问某些控制的所有孩子,你可以使用foreach
:
控制父= // ...
foreach (控制子 parent.Controls)
// 对孩子做点什么
你可能想要递归地做。
有时,使用控件的数组(集合)是个好主意。但设计师会为您提供每个控件的个人名称。该怎么办?两件事情。首先,您可以专门为此创建一个父控件,因此您可以枚举集合的控件Controls
,并且如果需要,可以在所有控件中引用所有控件。数组/集合,以便稍后通过索引访问它们,正如您在代码示例中所写的那样。
第二种方法是:设计人员不创建数组,所以 - 不要不要使用设计师。如果你有很多控件,在设计器中添加它们就是转储机械工作,难以维护,容易出错。以编程方式执行。然后你根本不需要所有这些控件的单独名称,因为对数组/集合对象的引用足以访问它们。
- SA
this is what I have on my form1:
checkBox0 ... to checkBox9 ==> in GroupBoxA
textBox0 ... to textBox9 ==> in GroupBoxB
richTextBox1
I want to access each Box in a Loop. like this
for (int i=0; i<=9; i++){
richTextBox.AppendText(checkBox[i]+textBox[i]);
}
The question makes little sense. How is that related to a group box, specifically?
If you want to access all children of some control, you can useforeach
:
Control parent = //... foreach(Control child in parent.Controls) // do something with child
You may want to do it recursively.
Sometimes, it's a good idea to use arrays (collections) of controls. But designer gives you individual name for each control. What to do? Two things. First, you can create a parent control specially for this purpose, so you can enumerate the controls of the collectionControls
, and, if needed, put reference to all of them in an array/collection, to later access them by index, as you wrote in your code sample.
Second approach is this: designer don't create arrays, so — don't use a designer. If you have many controls, adding them in the designer is the dump mechanical work, hard to maintain, error-prone. Do it programmatically. Then you won't need individual names for all those controls at all, because the reference to array/collection object is enough to access them all.
—SA
这篇关于如何访问像CheckBox或textBox这样的Group Box项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!