Couple of things to consider here ...
1. Your
comboBox1_SelectedIndexChanged
event is being fired as the comboBox is being populated, and the
SelectedIndex
equals zero at that point. So processing is dropping into your code, but before there is anything
actually selected.
One way around this is to unsubscribe from the
comboBox1_SelectedIndexChanged
event while you are populating the comboBox. e.g. like this
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
SqlCommand cmd = new SqlCommand("select * from Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
Then after you have populated the comboBox, you can subscribe to the event, and force a selection to happen e.g.
comboBox1.SelectedIndex = -1;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.SelectedIndex = 0;
2. Your comboBox1 is going to populated with numbers because you have used
comboBox1.DisplayMember = "County";
- there is no such column, it should be
Country
3. Never use string concatenation to build your sql statements like this
SqlDataAdapter da = new SqlDataAdapter("Select * From CountryState Where CountryId='" + comboBox1.SelectedValue + "'", con);
You leave yourself wide open to
SQL Injection attacks[
^] - use parameterized queries instead e.g.
SqlCommand cmd = new SqlCommand("Select * from StateCity Where StateId=@id", con);
cmd.Parameters.AddWithValue("@id", comboBox2.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(cmd);
4. You need to get into the habit of using some best practices such as
Try-Catch blocks[
^] and
using statements[
^]