I have a problems here, when I create a combo box in the coding I found that I am not able to set the selectedValue immediately after bind with the data source. The coding below is used to help me explain the problem.
I think I already found the problem, the problem might be something due with the synchronous. It means this line of code (comboBox1.SelectedIndex = 2) will execute before the combobox datasource is properly bind, so the combobox could not find the data when comboBox1.SelectedIndex = 2 is executed and generate errors. If I am wrong please correct me.
My solution is putting a while loop immediately after comboBox1.DataSource = data to make sure the combobox is bind properly before it can go to the next line of code. I am sure that this is not a good ways.
Does any others better solution for this?? Thanks in advance.
public partial class Form2 : Form
{
private ComboBox comboBox1 = new ComboBox();
public Form2()
{
InitializeComponent();
string[] data = { "a", "b", "c" };
comboBox1.DataSource = data;
//This line of code is used to confirm the data source
//is bind to the combo box
while (comboBox1.DataSource == null) ;
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
this.Controls.Add(comboBox1);
comboBox1.SelectedIndex = 2;
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("");
}
}
Just set the ComboBox.BindingContext
to a dummy instance.
string[] data = { "a", "b", "c" };
comboBox1.BindingContext = new BindingContext();
comboBox1.DataSource = data;
comboBox1.SelectedIndex = 2;