I have multiple ComboBoxes in my WinForms application, which all use the DropDownList style. They don't have a default value selected, and I want them to all have their first value show up automatically without the user having to select anything.
At first I tried setting each ComboBox's selectedValue by doing:
ComboBox1.SelectedIndex = 0;
But I wasn't sure where to put this code. Ideally, it would be executed once when each ComboBox is initialized, but I don't know if this is possible.
Then I thought I could put the code into the entire Form's load method:
private void GUI_Load(object sender, EventArgs e)
{
ComboBox1.SelectedIndex = 0;
ComboBox2.SelectedIndex = 0;
}
This works but this gets annoying as the number of ComboBoxes gets large. So I thought of looping like so:
private void GUI_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is ComboBox)
{
ComboBox combo = (ComboBox)c;
combo.SelectedIndex = 0;
}
}
}
This wouldn't work for some reason; the only Controls it looped over were only Panels and nothing else.
What am I doing wrong with this loop? What is the best solution here?