2

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?

catanasian
  • 73
  • 1
  • 7
  • Your controls are contained within panel(s). Check if c is Panel and then iterate though child controls of the panel(s). – Mikko Viitala Jun 20 '14 at 20:34
  • 1
    try something like this: [How to get ALL child controls of a Windows Forms form of a specific type ]: http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button – Dani Jun 20 '14 at 20:44
  • Clean and simple @MikkoViitala! Thanks. @Dani So is the only way to get all child controls through recursion? – catanasian Jun 23 '14 at 16:46

1 Answers1

1
/// <summary>
/// For use with Windows Forms
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="controlCollection"></param>
/// <param name="resultCollection"></param>
public static void GetControlsRecursiveWin<T>(System.Windows.Forms.Control.ControlCollection controlCollection, List<T> resultCollection) where T : System.Windows.Forms.Control
{
    foreach (System.Windows.Forms.Control control in controlCollection)
        {
            if (control is T)
                resultCollection.Add((T)control);

            if (control.HasChildren)
                GetControlsRecursiveWin(control.Controls, resultCollection);
        }
}

usage:

List<ComboBox> lstDDL = new List<ComboBox>();
GetControlsRecursiveWin<ComboBox>("<name of yourpanel>".Controls, lstDDL);

This will produce a list of all controls of type ComboBox within that control. Then you can iterate and set these controls to a desired value.

Dmitri E
  • 253
  • 1
  • 11