Home Asp.net DropDownList Cascading: Country-State-City Dependency in Asp.net

DropDownList Cascading: Country-State-City Dependency in Asp.net

77
0
DropDownList Country-State-City Cascading using Ajax
DropDownList Country-State-City Cascading using Ajax

In this tutorial, I’ll explain dropdownlist cascading in form of country-state-city that depends on one another in asp.net using c# as well as vb.net with example code.

In my previous tutorials, I’d explained about cascading country-state-city for dropdownlist without page refresh, dynamically bind and show data in dropdownlist, main differences between executereader executenonquery and executescalar and other more cracking tutorials on DropDownList, GridView, Asp.net here.

To explain further about cascading asp.net dropdownlist for country-state-city, we need to create database table to get data and bind retrieved resultset to dropdown list based on dropdown selections, so check out the following image that shows the relationship between country-state-city tables one another. If you want the database tables sample script, download sample code at the end of tutorial else do it by yourself.

Cascading Country State & Ciity Database Relationship Example
Cascading Country State & Ciity Database Relationship Example

HTML Markup For Asp.net DropDownList Cascading – [.aspx]

Following is the complete HTML Markup code that I used for this demonstration for asp.net dropdownlist cascading in my .aspx page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Simple cascading country-state-city dropdownlist example in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h4>Simple cascading country-state-city dropdownlist example in asp.net</h4>
            <table>
                <tr>
                    <td>Select Country:
                        <asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>Select State:
                        <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true"
                            OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>Select City:
                        <asp:DropDownList ID="ddlCity" runat="server">
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Now check the below sample code snippet to bind cascading country-state-city of asp.net dropdown list.

Country-State-City DropDownList Cascading In C# – [.cs]

Now add the following namespace that is required to connect with sql server:

using System.Data;
using System.Data.SqlClient;

After that add the following code to .aspx.cs page:

//specify your connection string here..
public static string strConn = @"Data Source=datasource;Integrated Security=true;Initial Catalog=database";

protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        BindCountryList();
    }
}
    
//bind countries to country dropdownlist
private void BindCountryList() {
    try {
        using (SqlConnection sqlConn = new SqlConnection(strConn)) {
            using (SqlCommand sqlCmd = new SqlCommand()) {
                sqlCmd.CommandText = "SELECT CountryId,CountryName FROM Country";
                sqlCmd.Connection = sqlConn;
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                ddlCountry.DataSource = dt;
                ddlCountry.DataValueField = "CountryId";
                ddlCountry.DataTextField = "CountryName";
                ddlCountry.DataBind();
                sqlConn.Close();
                //Adding "Please select country" option in dropdownlist
                ddlCountry.Items.Insert(0, new ListItem("Please select country", "0"));

                //Adding initially value to "state" and "city" dropdownlist
                ddlState.Items.Insert(0, new ListItem("Please select state", "0"));
                ddlCity.Items.Insert(0, new ListItem("Please select city", "0"));
            }
        }
    } catch { }
}

//bind states to state dropdownlist on country change event
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) {
    try {
        using (SqlConnection sqlConn = new SqlConnection(strConn)) {
            using (SqlCommand sqlCmd = new SqlCommand()) {
                sqlCmd.CommandText = @"SELECT StateId,StateName FROM State WHERE CountryId=@CountryId";
                sqlCmd.Parameters.AddWithValue("@CountryId", ddlCountry.SelectedValue);
                sqlCmd.Connection = sqlConn;
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                ddlState.DataSource = dt;
                ddlState.DataValueField = "StateId";
                ddlState.DataTextField = "StateName";
                ddlState.DataBind();
                sqlConn.Close();

                //Adding "Please select state" option in dropdownlist
                ddlState.Items.Insert(0, new ListItem("Please select state", "0"));

                //also clear city dropdownlist because we are changing country
                ddlCity.Items.Clear();
                ddlCity.Items.Insert(0, new ListItem("Please select city", "0"));
            }
        }
    } catch { }
}

//bind cities to city dropdownlist on state change event
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) {
    try {
        using (SqlConnection sqlConn = new SqlConnection(strConn)) {
            using (SqlCommand sqlCmd = new SqlCommand()) {
                sqlCmd.CommandText = @"SELECT CityId,CityName FROM City WHERE StateId=@StateId";
                sqlCmd.Parameters.AddWithValue("@StateId", ddlState.SelectedValue);
                sqlCmd.Connection = sqlConn;
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                ddlCity.DataSource = dt;
                ddlCity.DataValueField = "CityId";
                ddlCity.DataTextField = "CityName";
                ddlCity.DataBind();
                sqlConn.Close();

                //Adding "Please select city" option in dropdownlist
                ddlCity.Items.Insert(0, new ListItem("Please select city", "0"));
            }
        }
    } catch { }
}

Country-State-City DropDownList Cascading In Vb.net – [.vb]

Now add the following namespace that is required to connect with sql server:

Imports System.Data.SqlClient

After that add the following code to .aspx.vb page:

'specify your connection string here..'
Public Shared strConn As String = "Data Source=datasource;Integrated Security=true;Initial Catalog=database"

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindCountryList()
    End If
End Sub

'bind countries to country dropdownlist'
Private Sub BindCountryList()
    Try
        Using sqlConn As New SqlConnection(strConn)
            Using sqlCmd As New SqlCommand()
                sqlCmd.CommandText = "SELECT CountryId,CountryName FROM Country"
                sqlCmd.Connection = sqlConn
                sqlConn.Open()
                Dim da As New SqlDataAdapter(sqlCmd)
                Dim dt As New DataTable()
                da.Fill(dt)
                ddlCountry.DataSource = dt
                ddlCountry.DataValueField = "CountryId"
                ddlCountry.DataTextField = "CountryName"
                ddlCountry.DataBind()
                sqlConn.Close()

                'Adding "Please select country" option in dropdownlist'
                ddlCountry.Items.Insert(0, New ListItem("Please select country", "0"))

                'Adding initially value to "state" and "city" dropdownlist'
                ddlState.Items.Insert(0, New ListItem("Please select state", "0"))
                ddlCity.Items.Insert(0, New ListItem("Please select city", "0"))
            End Using
        End Using
    Catch
    End Try
End Sub

'bind states to state dropdownlist on country change event'
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Try
        Using sqlConn As New SqlConnection(strConn)
            Using sqlCmd As New SqlCommand()
                sqlCmd.CommandText = "SELECT StateId,StateName FROM State WHERE CountryId=@CountryId"
                sqlCmd.Parameters.AddWithValue("@CountryId", ddlCountry.SelectedValue)
                sqlCmd.Connection = sqlConn
                sqlConn.Open()
                Dim da As New SqlDataAdapter(sqlCmd)
                Dim dt As New DataTable()
                da.Fill(dt)
                ddlState.DataSource = dt
                ddlState.DataValueField = "StateId"
                ddlState.DataTextField = "StateName"
                ddlState.DataBind()
                sqlConn.Close()

                'Adding "Please select state" option in dropdownlist'
                ddlState.Items.Insert(0, New ListItem("Please select state", "0"))

                'also clear city dropdownlist because we are changing country'
                ddlCity.Items.Clear()
                ddlCity.Items.Insert(0, New ListItem("Please select city", "0"))
            End Using
        End Using
    Catch
    End Try
End Sub

'bind cities to city dropdownlist on state change event'
Protected Sub ddlState_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Try
        Using sqlConn As New SqlConnection(strConn)
            Using sqlCmd As New SqlCommand()
                sqlCmd.CommandText = "SELECT CityId,CityName FROM City " &
                "WHERE StateId=@StateId"
                sqlCmd.Parameters.AddWithValue("@StateId", ddlState.SelectedValue)
                sqlCmd.Connection = sqlConn
                sqlConn.Open()
                Dim da As New SqlDataAdapter(sqlCmd)
                Dim dt As New DataTable()
                da.Fill(dt)
                ddlCity.DataSource = dt
                ddlCity.DataValueField = "CityId"
                ddlCity.DataTextField = "CityName"
                ddlCity.DataBind()
                sqlConn.Close()

                'Adding "Please select city" option in dropdownlist'
                ddlCity.Items.Insert(0, New ListItem("Please select city", "0"))
            End Using
        End Using
    Catch
    End Try
End Sub

Example Result

Get data from database and bind to asp.net dropdownlist using c# vb.net
Get data from database and bind to asp.net dropdownlist using c# vb.net

Download Example

Git Repo

Previous articleBind Asp.net DropDownList Dynamically In C# Vb.net
Next articleDropDownList Country-State-City Cascading using Ajax
Hi there, I am Mayank, the man behind Technical Mack. I started AspnetO with a motive to educate people on various programming languages ranging from beginners to expert level. Through this blog, I aim to provide more insightful content.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

eight + 18 =