In this article I will explain with an example, how to populate Cascading DropDownList from
SQL Server in ASP.Net using C# and VB.Net.
Note: Cascading DropDownLists are series of DropDownList where the ListItem of each DropDownList is depend on the selection made in the previous one.
Database
I have made use of the following three tables Countries, States and Cities with the schema as follows.
Countries Table
States Table
Cities Table
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following controls:
DropDownList – For selecting data from database in DropDownList.
Properties
The DropDownList have been assigned with the AutoPostBack property set to TRUE.
Event Handlers
The DropDownList have been assigned with an OnSelectedIndexChanged event handler.
<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" AutoPostBack="true" OnSelectedIndexChanged="City_Changed"></asp:DropDownList>
</td>
</tr>
</table>
Populating the DropDownList from Database using C# and VB.Net
The BindDropDownList method will be called to populate DropDownList based on selection of the current DropDownList.
This method accepts the reference of the DropDownList, the SQL Query, and the name of the Columns to be set in DataTextField and DataValueField properties of DropDownList respectively and a DefaultText.
Inside this method, the accepted SQL query is passed as parameter to
SqlCommand class and using its
ExecuteReader method, the records are fetched from the
SQL Server database.
Finally, the referenced DropDownList will be populated and the DefaultText is set to the 0th position of DropDownList.
C#
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
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"));
}
VB.Net
Private Sub BindDropDownList(ByVal ddl As DropDownList, ByVal query As String, ByVal text As String, ByVal value As String, ByVal defaultText As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
con.Open()
ddl.DataSource = cmd.ExecuteReader()
ddl.DataTextField = text
ddl.DataValueField = value
ddl.DataBind()
con.Close()
End Using
End Using
End Using
ddl.Items.Insert(0, New ListItem(defaultText, "0"))
End Sub
Populating the Country DropDownList from Database
Inside the Page Load event handler, the DropDownList for displaying Country names is populated by making call to the BindDropDownList generic method (explained earlier).
Then, the Enabled property of DropDownList for displaying State and City names is set to FALSE and DefaultText is also set.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT CountryId,CountryName FROM Countries";
this.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"));
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim query As String = "SELECT CountryId,CountryName FROM Countries"
Me.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"))
End If
End Sub
Populating the State DropDownList from Database
When selection of Country DropDownList is changed, the value of the CountryId is fetched and SELECT query along with the ID of the DropDownList for displaying State and required details are passed as parameter to BindDropDownList method (explained earlier).
Finally, the Enabled property of the DropDownList for displaying State names is set to TRUE.
C#
protected void Country_Changed(object sender, EventArgs e)
{
int countryId = int.Parse(ddlCountries.SelectedItem.Value);
if (countryId > 0)
{
string query = string.Format("SELECT StateId,StateName FROM States WHERECountryId = {0}", countryId);
this.BindDropDownList(ddlStates, query, "StateName", "StateId", "Select State");
ddlStates.Enabled = true;
}
}
VB.Net
Protected Sub Country_Changed(ByVal sender As Object, ByVal e As EventArgs)
Dim countryId As Integer = Integer.Parse(ddlCountries.SelectedItem.Value)
If countryId > 0 Then
Dim query As String = String.Format("SELECT StateId, StateName FROM States WHERE CountryId = {0}", countryId)
Me.BindDropDownList(ddlStates, query, "StateName", "StateId", "Select State")
ddlStates.Enabled = True
End If
End Sub
Populating the City DropDownList from Database
When selection of State, the value of the StateId is fetched and SELECT query along with the ID of the DropDownList for displaying City and required details are passed as parameter to BindDropDownList method (explained earlier).
Finally, the Enabled property of the DropDownList for displaying City names is set to TRUE.
C#
protected void State_Changed(object sender, EventArgs e)
{
int stateId = int.Parse(ddlStates.SelectedItem.Value);
if (stateId > 0)
{
string query = string.Format("SELECT CityId, CityName FROM Cities WHEREStateId = {0}", stateId);
this.BindDropDownList(ddlCities, query, "CityName", "CityId", "Select City");
ddlCities.Enabled = true;
}
}
VB.Net
Protected Sub State_Changed(ByVal sender As Object, ByVal e As EventArgs)
Dim stateId As Integer = Integer.Parse(ddlStates.SelectedItem.Value)
If stateId > 0 Then
Dim query As String = String.Format("SELECT CityId, CityName FROM Cities WHEREStateId = {0}", stateId)
Me.BindDropDownList(ddlCities, query, "CityName", "CityId", "Select City")
ddlCities.Enabled = True
End If
End Sub
Displaying Selected Item of DropDownLists
When selection of City DropDownList is changed, the selected item of each DropDownList is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
Finally, the Enabled property of DropDownList for displaying State and City names is set to FALSE.
C#
protected void City_Changed(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Country: " + ddlCountries.SelectedItem.Text +
"\\nState: " + ddlStates.SelectedItem.Text +
"\\nCity: " + ddlCities.SelectedItem.Text + "');", true);
ddlStates.Enabled = false;
ddlCities.Enabled = false;
}
VB.Net
Protected Sub City_Changed(ByVal sender As Object, ByVal e As EventArgs)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Country: " & ddlCountries.SelectedItem.Text &
"\nState: " & ddlStates.SelectedItem.Text &
"\nCity: " & ddlCities.SelectedItem.Text & "');", True)
ddlStates.Enabled = False
ddlCities.Enabled = False
End Sub
Screenshot
Downloads