Thursday, 6 June 2013

Cascading DropDownList for Country/State/City in ASP.Net

Cascading DropDownList for Country/State/City in ASP.Net

Database
For this example I have created a SQL Server database named Cascading_ddl, the script of which is attached along with the sample code.
In this database I have created tables for storing Country, State and City named as Countries, States and Cities respectively with schema shown below
Countries Table
country state city drop down list using ajax in asp.net

States Table
country state city drop down list in asp.net with c#

Cities Table
cascading dropdownlist for country/state/city in asp.net

Creating the Database
You will have to simply execute the script named CreateCascadingDatabase.sql stored in the SQL Folder of the attached sample and it will create the complete database with data.
 
HTML Markup
Below is the HTML Markup which contains three ASP.Net DropDownList controls each for Country, State and City. I have placed all the three DropDownLists inside ASP.Net UpdatePanel control to avoid full PostBack and make use of AJAX.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <table>
            <tr>
                <td>Country:</td>
                <td><asp:DropDownList ID="ddlCountries" runat="server" AutoPostBack = "true"OnSelectedIndexChanged = "Country_Changed">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>State:</td>
                <td>
                    <asp:DropDownList ID="ddlStates" runat="server" AutoPostBack = "true" OnSelectedIndexChanged= "State_Changed">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>City:</td>
                <td>
                    <asp:DropDownList ID="ddlCities" runat="server">
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>
 

 Generic function to Bind and populate the ASP.Net DropDownList
Below is the generic function that will be used to populate and bind the ASP.Net DropDownList with data from the SQL Server Database
C#
private void BindDropDownList(DropDownList ddl, string query, string text, string value, stringdefaultText)
{
    string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            ddl.DataSource = cmd.ExecuteReader();
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
            con.Close();
        }
    }
    ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}


Populating the Country DropDownList
The Country DropDownList is populated on Page_Load event of the page as shown below
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select CountryId, CountryName from Countries";
        BindDropDownList(ddlCountries, query, "CountryName""CountryId""Select Country");
        ddlStates.Enabled = false;
        ddlCities.Enabled = false;
        ddlStates.Items.Insert(0, new ListItem("Select State""0"));
        ddlCities.Items.Insert(0, new ListItem("Select City""0"));
    }
}



Populating the State DropDownList
The State DropDownList is populated on OnSelectedIndexChanged event of the Country DropDownList as shown below
C#
protected void Country_Changed(object sender, EventArgs e)
{
    ddlStates.Enabled = false;
    ddlCities.Enabled = false;
    ddlStates.Items.Clear();
    ddlCities.Items.Clear();
    ddlStates.Items.Insert(0, new ListItem("Select State""0"));
    ddlCities.Items.Insert(0, new ListItem("Select City""0"));
    int countryId = int.Parse(ddlCountries.SelectedItem.Value);
    if (countryId > 0)
    {
        string query = string.Format("select StateId, StateName from States where CountryId = {0}", countryId);
        BindDropDownList(ddlStates, query, "StateName""StateId""Select State");
        ddlStates.Enabled = true;
    }
}

Populating the City DropDownList
The City DropDownList is populated on OnSelectedIndexChanged event of the State DropDownList as shown below
C#
protected void State_Changed(object sender, EventArgs e)
{
    ddlCities.Enabled = false;
    ddlCities.Items.Clear();
    ddlCities.Items.Insert(0, new ListItem("Select City""0"));
    int stateId = int.Parse(ddlStates.SelectedItem.Value);
    if (stateId > 0)
    {
        string query = string.Format("select CityId, CityName from Cities where StateId = {0}", stateId);
        BindDropDownList(ddlCities, query, "CityName""CityId""Select City");
        ddlCities.Enabled = true;
    }
}
 

No comments:

Post a Comment