I have a form with sixteen combo-boxes, each with the DropDownStyle
property set to DropDownList
. I am trying to set the form so each control shows its first pre-defined value:
private void Form1_Load(object sender, EventArgs e)
{
foreach (ComboBox DropDown in this.Controls.OfType<ComboBox>())
DropDown.SelectedIndex = 0;
}
This code is not working, although individually assigning each item does. Any ideas why?
My WinForm experience is a bit rusty, but if I remember correctly, this.Controls
will only bring you those controls directly under the main Form. If you have any subcontrols, like a Groupbox, they will be under that groupbox's .Controls
.
You can either explicitly iterate your Groupbox's controls, or you can use recursion to go over all child controls of the form, like you can see here.