How to set ComboBox index?

Viewed 125

"I understand question title may be repeated but did not find a solution which I am looking for."

A groupbox which contains approx 50 controls in the combination of textboxes and comboBoxes. I have to set value for them and don't want to write 50 individual lines to set value for each control, so I came up with below code. But this is not working in case of comboboxes. OR If you guys can suggest something better that would be great.

if(controlsInGroupBox == editStep.Count)
{
    int i = 0;
    foreach (Control ctr in universalGroupBoxObject.Controls)
    {  
        if (ctr is TextBox)
        {
            ctr.Text = editStep[i];
        }
        if (ctr is ComboBox)
        {
            //ctr.SelectedIndex = cntrlObjListMain.comboBoxLocation.FindStringExact(editStep[i]);
           //ctr.SelectedIndex is not working
         }
        i++;
    }
}
1 Answers

If you databind your data to the combobox then the first item is selected by default saving you having to select one.

E.G.

List<string> items = new List<string>() { "aa", "bb", "cc", "dd" };

combobox1.DataSource = items;

SelectedIndex should work as long as you have items in your list.

ctr.SelectedIndex = ctr.Items.Count > 0 ? 0 : -1;

The above will select an item if there are any items, otherwise won't select anything.

Related