foreach statement cannot operate on variables of type
‘System.Windows.Controls.GroupBox’ because
‘System.Windows.Controls.GroupBox’ does not contain a public
definition for ‘GetEnumerator’
mycode :
foreach (var txt in this.groupBox1.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
But why is the correct code for the Grid ?
foreach (var txt in this.MyGrid.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
What is the correct code for groupBox?
/////////////////editing
Correct code:
foreach (var txt in this.MyGridInGroupBox.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
Your first snippet won’t even compile (assuming
groupBox1is indeed aGroupBox), sinceGroupBoxhas noChildrenproperty.A
GroupBoxcan only contain one child, represented by itsContentproperty.If you need to iterate over all the visual children of a
GroupBox, you might be able to use theVisualTreeHelperclass. Something like this:Update
Ok, you’re saying that this doesn’t work, and I think I understand why.
The
VisualTreeHelperwill only find the first-level visual children of theGroupBox, which (as the control is implemented) is aGrid.This is no good to you, because you need to recurse down into the children of the control and find all the TextBoxes.
In that case, you’re better off using one of the many recursve “FindChildren” implementations around the web. Here’s one of mine:
You can use that like this: