Search code examples
c#winformscombobox

ComboBox.SelectedValue not working


What is wrong with this code?

myComboBox.Items.Clear();
myComboBox.Items.AddRange(new string[]{"one","two"});
myComboBox.SelectedValue = "one";

It is showing up with nothing selected.


Solution

  • If you populate the combobox like this:

    myComboBox.Items.AddRange(new string[]{"one","two"});
    

    You must use the ComboBox.SelectedItem or the ComboBox.SelectedIndex property to set/get the selected item:

    myComboBox.SelectedItem = "one"; //or
    myComboBox.SelectedIndex = 0; 
    

    The ComboBox.SelectedValue property is inherited from ListControl and must be used ONLY when:

    • the control is bound to a DataSource
    • and ValueMember and DisplayMember properties are definied.