Reputation: 3
I've been trying to fill data into dropdown list from the database. I want to select values from two dropdown lists and want to fill the third dropdown list with data corresponding to the dropdown list values in database. But the third ddl will always be empty.
protected void ddl3_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ddl3.Items.Clear();
s = "SELECT subject FROM subjects WHERE branch='" + ddl1.SelectedItem.Value + "' AND sem='" + ddl2.SelectedItem.Value + "'";
ds = dc.getdata(s);
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
ddl3.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
Suppose the values in database are branch=IT, sem=I sem and sub=ML. On selecting IT in the first ddl, and I sem in second ddl, the third ddl should show ML and other data corresponding to this branch and sem.
Upvotes: 0
Views: 143
Reputation: 65
Your are filling wrong, you should fill into ddl2_SelectedIndexChanged like below
protected void ddl2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ddl3.Items.Clear();
s = "SELECT subject FROM subjects WHERE branch='" + ddl1.SelectedItem.Value + "' AND sem='" + ddl2.SelectedItem.Value + "'";
ds = dc.getdata(s);
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
ddl3.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
If you write code into 2nd dropdown list select index then you pass dropdown1 value and dropdown2 value.
Related example
http://www.dotnetfunda.com/codes/show/5512/dropdownlist-with-country-state-and-city-in-asp-net
Upvotes: 1
Reputation: 2457
You don't want to fill your ddl3 which is dependant on ddl1 and 2 in the ddl3 handler (ddl3_selected_index_changed), because the index can not change when there is no options to select from. After filling it make sure it is not overwritten before it's handler is called. This is most easily done by filling ddl3 in PreRender. However that creates many unneeded database accesses. It is better to fill ddl3 in the handlers for ddl1 and ddl2.
Upvotes: 0