Implement Cascading (Dependent) ListBox in ASP.Net

In this post, I’ll demonstrate how to use C# to construct a cascading (dependent) ListBox from a database in ASP.Net.

Database

I used the following three tables: Cities, States, and Countries, using the following schema.

Countries Table

HTML Markup

For Country, State, and City, there are three ListBoxes each in the following HTML Markup.
SelectedIndexChanged event handlers have been added to the State and Country ListBoxes, and the AutoPostBack attribute has been set to True.

<table>
    <tr>
        <td>Country:</td>
        <td>
            <asp:ListBox ID="lstCountries" runat="server" AutoPostBack="true"
                OnSelectedIndexChanged="OnCountryChanged"></asp:ListBox>
        </td>
    </tr>
    <tr>
        <td>State:</td>
        <td>
            <asp:ListBox ID="lstStates" runat="server" AutoPostBack="true"
                OnSelectedIndexChanged="OnStateChanged"></asp:ListBox>
        </td>
    </tr>
    <tr>
        <td>City:</td>
        <td>
            <asp:ListBox ID="lstCities" runat="server"></asp:ListBox>
        </td>
    </tr>
</table>

Namespaces

You must import the namespaces listed below.

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

Generic function to populate ListBox from Database

The ListBox reference, the SQL query, the name of the column to be displayed in the Text part, and the name of the column to be displayed in the Value portion are all parameters that can be passed to the following function.
Finally, the SQL query is run, and database data is inserted into the ListBox.

private void BindListBox(ListBox lst, string query, string text, string value)
{
    string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open();
            lst.DataSource = cmd.ExecuteReader();
            lst.DataTextField = text;
            lst.DataValueField = value;
            lst.DataBind();
            con.Close();
        }
    }
}

Populating the Country ListBox from Database

The BindListBox generic function is used to populate the Country ListBox with data from the database inside the Page Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string query = "SELECT CountryId, CountryName FROM Countries";
        this.BindListBox(lstCountries, query, "CountryName", "CountryId");
    }
}

Populating the State ListBox from Database

The State ListBox is filled from the database using the BindListBox generic function utilising the selected value of the Country inside the SelectedIndexChanged event handler of the Country ListBox.

protected void OnCountryChanged(object sender, EventArgs e)
{
    lstStates.Items.Clear();
    lstCities.Items.Clear();
    int countryId = int.Parse(lstCountries.SelectedItem.Value);
    if (countryId > 0)
    {
        string query = string.Format("SELECT StateId, StateName FROM States WHERE CountryId = {0}", countryId);
        this.BindListBox(lstStates, query, "StateName", "StateId");
    }
}

Populating the City DropDownList from Database

The City ListBox is filled from the database using the BindListBox generic function using the selected value of the State inside the State ListBox’s SelectedIndexChanged event handler.

protected void OnStateChanged(object sender, EventArgs e)
{
    lstCities.Items.Clear();
    int stateId = int.Parse(lstStates.SelectedItem.Value);
    if (stateId > 0)
    {
        string query = string.Format("SELECT CityId, CityName FROM Cities WHERE StateId = {0}", stateId);
        this.BindListBox(lstCities, query, "CityName", "CityId");
    }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories