Windows Forms - Iterating through controls on a form
I have a form with many groupboxes (18) and within each groupbox are controls (textboxes and checkboxes). When the user clicks the "NEW" button, I want to clear all controls on the form for data entry. I figured I would generically iterate through all the controls on the form and clear the information accordingly (set textbox.text = "" or checkbox.checked == false). I can get to all the groupboxes but can figure out how to iterate the controls within each groupbox.
Here is my psuedo code:
foreach (Control c in this.Controls)
{
//check for a groupbox
if (c is GroupBox)
{
}
}
AlanPosted Jun 14, 2007, 6:58 PM
DanielPosted Jun 14, 2007, 3:56 PM
DanielPosted Jun 14, 2007, 3:55 PM
AlanPosted Jun 14, 2007, 3:52 PM
GroupBox gb = (GroupBox)c;
To assign 'c' to the GroupBox variable, we have to cast it to it's actual type and so, yes (GroupBox) means cast the following expression to GroupBox. If you didn't use the cast, you'd find that the compiler would complain that there is no implicit conversion from Control to GroupBox.
You can only use a 'switch' statement with variables of bool, string or one of the integer types (including enums), so it's better to use an 'if' statement here.
DanielPosted Jun 14, 2007, 2:47 PM
AlanPosted Jun 14, 2007, 2:33 PM
See if this will work:
foreach (Control c in this.Controls)
{
if (c is GroupBox)
{
GroupBox gb = (GroupBox)c;
foreach(Control cc in gb.Controls)
{
if(cc is TextBox)
{
TextBox tb = (TextBox)cc;
tb.Text = "";
}
else if (cc is CheckBox)
{
CheckBox cb = (CheckBox)cc;
cb.Checked = false;
}
}
}
}