Search code examples
c#.netwinformscombobox

Selecting default item from Combobox C#


I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

SelectPrint11.SelectedIndex=2;

but error is:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection


Solution

  • You can set using SelectedIndex (which uses a zero-based index)

    comboBox1.SelectedIndex = 0;
    

    OR

    SelectedItem

    comboBox1.SelectedItem = "your value"; // 
    

    The latter won't throw an exception if the value is not available in the combobox

    EDIT

    If the value to be selected is not specific then you would be better off with this

    comboBox1.SelectedIndex = comboBox1.Items.Count - 1;