Search code examples
c#.netwinformscombobox

How to set Selected item of ComboBox in C# Windows Forms?


I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.

For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.

Not working code:

for (int i = 0; i < cmbVendor.Items.Count; i++)

    if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
    {
        cmbVendor.SelectedIndex = i;
        break;
    }

Solution

  • You can get your item index by the .Items.IndexOf() method. Try this:

    comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
    

    You don't need to iterate.

    You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.