I'm having trouble installing SelectedIndex on a linked ComboBox (on a Windows form), which I add to the form at runtime, and I suspect something strange is happening.
When I try to do this, I get the error message "InvalidArgument = value" 1 "is not valid for" SelectedIndex "."
private void Form1_Load(object sender, EventArgs e) { List<string> comboBoxList = new List<string>(); comboBoxList.Add("Apples"); comboBoxList.Add("Oranges"); comboBoxList.Add("Pears"); ComboBox comboBox1 = new ComboBox(); comboBox1.DataSource = comboBoxList; comboBox1.SelectedIndex = 1; this.Controls.Add(comboBox1); }
However, there is no problem if I add elements directly to the ComboBox, for example:
comboBox1.Add("Apples");
Also, there is no problem if I add a control to the form before I set SelectedIndex, for example:
ComboBox comboBox1 = new ComboBox(); this.Controls.Add(comboBox1); comboBox1.DataSource = comboBoxList; comboBox1.SelectedIndex = 1;
Can someone explain why I cannot set the selected index from the data source until the control is added to the form?
source share