AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / DropDownList Cascading: Country-State-City Dependency in Asp.net

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

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Oct 05, 2020

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.

country-state-city-database-relationship

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>
Tip: Check how to get connection string to connect SQL database in asp.net?

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
You may also like, 100+ Frequently Asked Interview Questions on Asp.net, Top 10 OOPS Concepts in .NET C# with Examples here.

Download Example

Icon

Bind Asp.net DropDownList Examples

1 file(s) 46.14 KB
Download This Example

Git Repo

git clone https://github.com/immayankmodi/bind-dropdown-list-asp-net-c-vb.git

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Leave a Reply Cancel reply

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,098 Followers
  • 51 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Asp.net TextBox: How to Get Set TextBox Value or Text in JavaScript
  • Show Confirm Message Box from Code-behind in Asp.net
  • Show Alert Message Box from Code-behind in Asp.net C# Vb
  • Top 10 OOPS Concepts In C# .NET With Examples

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous Bind Asp.net DropDownList Dynamically In C# Vb.net
Next DropDownList Country-State-City Cascading using Ajax