Reputation:
I have a Windows form that have some GroupBox, i want to set all textbox.text in Groupboxes to 0. i wrote this code but not working.
foreach (var TTX in this.Controls)
{
if (TTX is TextBox)
((TextBox) TTX).Text = (0).ToString(format: "c0");
}
Upvotes: 0
Views: 569
Reputation: 216343
A direct approach as your code above cannot work if the controls to handle are inside another control container. And GroupBox is a control container. So you need to enumerate all the groupbox and the controls inside that groupboxes. However you can simplify a lot your code if you use the OfType enumerable to extract, first all groupboxes from the controls collection of the form, then, foreach groupbox use the same technique to extract just the textboxes contained in the controls collection of the current GroupBox. The advantage is clear if you see how the code doesn't need anymore complicated checks and casts to use a TextBox or GroupBox strong typed variable.
foreach (var grpBox in this.Controls.OfType<GroupBox>())
{
foreach(var TTX in grpBox.Controls.OfType<TextBox>())
TTX.Text = 0.ToString(format: "c0");
}
Upvotes: 2