简体   繁体   中英

Dropdown list with database connection

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM