Cascading DropDownList


This code describe how to manupulate dependent dropdownlist

This code how to manupulate cascading droplist.Cascading dropdownlist means dependent dropDownLists where one DropDownList is dependent on other dropDownList.
Programmer need to many occasions where bind dropdownlist on selection of another dropdownlist.

Steps:
Take three dropdownlist in aspx page
1.ddlCountry- List of Countries
2.ddlState - list of states
2.ddlCity - List of Cities


if (!Page.IsPostBack)
{
CountryBind();
}
protected void CountryBind()
{
string sqlQuery = "Select * from Country;

using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataBind();
conn.Close();
}
}
protected void StateBind()
{
string sqlQuery = "SELECT * FROM State " + " WHERE (CountryId = " + Convert.ToInt32(ddlCountry.SelectedValue) + " )";

using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlState.DataSource = ds;
ddlState.DataBind();
conn.Close();
}
}
protected void CityBind()
{
string sqlQuery = "SELECT * FROM City " + " WHERE (StateId = " + Convert.ToInt32(ddlState.SelectedValue) + " )";

using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlCity.DataSource = ds;
ddlCity.DataBind();
conn.Close();
}
}

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
StateBind();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
CityBind();
}


aspx page code

<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" DataTextField="CountryName"
DataValueField="CountryId" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
<asp:ListItem Value="0" Text="<Select Country> "> </asp:ListItem>
</asp:DropDownList>

<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" DataTextField="StateName"
DataValueField="StateId" OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
</asp:DropDownList>

<asp:DropDownList ID="ddlCity" runat="server" DataTextField="CityName" DataValueField="CityId">
</asp:DropDownList>


Related Articles

More articles: Cascading DropDownList DropDownList add items DropDownList data binding

Comments

Guest Author: shivakumar29 Oct 2012

thanku it helps me a lot,
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
StateBind();
CityBind();//I THINK, U SHOULD ADD THIS FOR BETTER OUTPUT
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: