In ComboBox, when DataSource is set but SelectedIndex = 0 is set, an exception occurs

less than 1 minute read

Failure


comboBox.DataSource = ItemList; //ItemList is a list of entity classes SELECTed from DB
comboBox.SelectedIndex = 0;

//When you run the above code, System.ArgumentOutOfRangeException occurs.
//Unhandled exception. System.ArgumentOutOfRangeException: '0'InvalidArgument of=Value is'SelectedIndex'Not valid for.(Parameter 'value')
//Actual value was 0.

Running the CreateControl method before setting SelectedIndex worked (index 0 value was set to SelectedValue)

success


comboBox.DataSource = ItemList;
comboBox.CreateControl();
comboBox.SelectedIndex = 0;

Environment C # (.net 5 / C # 8.0)

Tags:

Updated: