我在groupbox中有几个文本框,我想循环遍历它们并从List(数组)中添加字符串。
我试过了:
foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox1 => groupBox1.Controls.OfType<TextBox>()))
{
textBox.Text = List[counter];
counter++;
}
但它对我不起作用,没有任何反应。
答案 0 :(得分:2)
这是一种方式:它假设组框中有多种类型的控件。如果只有文本框,则可以简化它。
private void button1_Click(object sender, EventArgs e)
{
int Counter = 0;
foreach (Control control in groupBox1.Controls)
{
TextBox textBox = control as TextBox;
if (textBox != null)
textBox.Text = Counter++.ToString();
}
}
答案 1 :(得分:1)
试试这个
foreach(var groupBox in Controls.OfType<GroupBox>()) {
foreach(var textBox in groupBox.Controls.OfType<TextBox>()) {
// Do Something
}
}
答案 2 :(得分:0)
你能尝试一下。
foreach (TextBox txt in Controls.OfType<GroupBox>().SelectMany(g=>g.Controls.OfType<TextBox>()).ToList())
{
//Write your logic here
}
答案 3 :(得分:0)
更清洁的方法是
foreach(Control control in groupBox1.Controls)
{
// Check if the object is indeed what we need
if(!(control is TextBox))
continue;
// "Cast" the object to a TextBox
TextBox textBox = control as TextBox;
// Do your thing with the textboxes
}