3

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.

Chris
  • 8,527
  • 10
  • 34
  • 51
JS_Riddler
  • 1,443
  • 2
  • 22
  • 32

2 Answers2

10

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.
Community
  • 1
  • 1
Chris
  • 8,527
  • 10
  • 34
  • 51
1

A couple of different options:

1) change SelectedValue to SelectedIndex

myComboBox.SelectedIndex = 0; //your first item

Please ignore this, this is for asp.net

2) add in ListItems manualy

myComboBox.Items.Clear();
myComboBox.Items.Add(new ListItem() { Text = "one", Selected = true };
myComboBox.Items.Add(new ListItem() { Text = "two" };

Just make sure you don't have more than one item selected at a given time.

gunr2171
  • 16,104
  • 25
  • 61
  • 88