C # databound ComboBox: InvalidArgument = Value '1' is not valid for 'SelectedIndex'

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?

+4
source share
1 answer

My understanding is that data binding is handled by the bindingcontext normaly constant, this is the parent forms of the bindingcontext. Therefore, the binding of the data source does not occur until you add comboBox to the form. You can also make this work if you set the bindbtext comboBox in the context of the form binding.

 comboBox1.BindingContext = this.BindingContext; comboBox1.DataSource = comboBoxList; comboBox1.SelectedIndex = 1; this.Controls.Add(comboBox1); 

BindingContext Class

What is a BindingContext?

+5
source

All Articles