Series DropDownList: Cascading DropDownList

This is the second article on the subject of DropDownList. If for any reason you missed the earlier post titled Series DropDownList: Binding XML Data to a DropDownList, I would recommend that you take the time and read that post as well.

In part two of this series I will focus on accomplishing cascading selections with your DropDownList. Since the bulk of the work was accomplished in DropDownList: Binding XML Data to a DropDownList we will pick up from there.

dropdown list bound with xml data

Web Form

Here we will incorporate a small change from the previous example. Notice that in this example I have added a new event titled OnSelectedIndexChanged.

<label for="ddlCountry">Country:</label>
<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" Width="160px">
</asp:DropDownList>
<label for="ddlRegion">Region:</label>
<asp:DropDownList ID="ddlRegion" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlRegion_SelectedIndexChanged" Width="160px">
</asp:DropDownList>
<label for="ddlCity">City:</label>
<asp:DropDownList ID="ddlCity" runat="server" Width="160px">
</asp:DropDownList>

Code Behind

Each selected index change event fires the appropriate method which in turns makes a call back to the server and reads in the appropriate data to return and bound to out DropDownList.

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
ddlRegion.Items.Clear();
string strCountry = string.Empty;
strCountry = ddlCountry.SelectedValue;
List<string> list = null;

if (ddlCountry.SelectedIndex != 0)
{
list = RetrieveDataFromXml.GetRegionByCountry(strCountry);
if (list != null && list.Count != 0)
{
ddlRegion.Enabled = true;
}

ddlRegion.DataSource = list;
ddlRegion.DataBind();
}
else
{
ddlRegion.Enabled = false;
}

ddlRegion.Items.Insert(0, new ListItem("Select Region", "-1"));

ddlCity.Enabled = false;
ddlCity.Items.Clear();
ddlCity.Items.Insert(0, new ListItem("Select City", "-1"));
}

protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
{
string strRegion = string.Empty;
strRegion = ddlRegion.SelectedValue;
List<string> list = null;
list = RetrieveDataFromXml.GetCityByRegion(strRegion);
ddlCity.Items.Clear();
ddlCity.DataSource = list;
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("Select City", "-1"));

if (list.Count > 0)
{
ddlCity.Enabled = true;
}
else
{
ddlCity.Enabled = false;
}
}

Conclusion

That is all it takes to produce a cascading DropDownList. In the event that you did not pick up that each DropDownList was posting back to the server revisit the example code in the web form and you will notice AutoPostBack=”True”.

Leave a Reply

Required fields are marked *.