ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Creating Cascading DropDownLists in ASP.Net
Author Name: Mudassar Khan Published Date: June 13, 2009
Filed Under :
ASP.Net
Views: 8927

Cascading DropDownList means a series of dependent DropDownLists where one DropDownList is dependent on the parent or previous DropDownList and is populated based on the item selected by the user. On many occasions we need to make use of Cascading DropDownLists as I have here

Continent - Country - City

City is dependent on Country and in turn Country is dependent on the Continent thus we need a series of Cascading DropDownList here.

 

Database Design

For this tutorial I have created three tables whose designs are given below

Continents Table


Continents Table Design


Countries Table


Countries Table Design

Cities Table


Cities Table Design

Connection String


<connectionStrings>

  <add name="conString" connectionString="Data Source=.\SQLEXPRESS;

    database=CascadingDDL;Integrated Security=true"/>

</connectionStrings>

 

Front End Design


I have used 3 DropDownLists one for each entity the mapping is shown below

1. ddlContinents - List of Continents

2. ddlCountry- List of Countries

3. ddlCity - List of Cities

   

        

<span style ="font-family:Arial">Select Continent : </span>

<asp:DropDownList ID="ddlContinents" runat="server" AutoPostBack = "true"

             OnSelectedIndexChanged="ddlContinents_SelectedIndexChanged">

<asp:ListItem Text = "--Select Continent--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<span style ="font-family:Arial">Select Country : </span>

<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack = "true"

Enabled = "false"  OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">

<asp:ListItem Text = "--Select Country--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<span style ="font-family:Arial">Select City : </span>

<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack = "true"

 Enabled = "false" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">

<asp:ListItem Text = "--Select City--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<asp:Label ID="lblResults" runat="server" Text="" Font-Names = "Arial" />

 

I have added OnSelectedIndexChanged Event to all DropDownLists and also AutoPostBack set property to true.

The User Interface looks as below


ScreenShot displaying 3 dropdownlists dependent on each other


Populating the Continents DropDownList


On the Page_Load Event of the Page I am populating the Continents DropDownList

        

C#

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        ddlContinents.AppendDataBoundItems = true;

        String strConnString = ConfigurationManager

            .ConnectionStrings["conString"].ConnectionString;

        String strQuery = "select ID, ContinentName from Continents";

        SqlConnection con = new SqlConnection(strConnString);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandType = CommandType.Text;

        cmd.CommandText = strQuery;

        cmd.Connection = con;

        try

        {

            con.Open();

            ddlContinents.DataSource = cmd.ExecuteReader();

            ddlContinents.DataTextField = "ContinentName";

            ddlContinents.DataValueField = "ID";

            ddlContinents.DataBind();

        }

        catch (Exception ex)

        {

            throw ex;

        }

        finally

        {

            con.Close();

            con.Dispose();

        }

    }

}

 

 

         

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

  If Not IsPostBack Then

    ddlContinents.AppendDataBoundItems = True

    Dim strConnString As [String] = ConfigurationManager _

             .ConnectionStrings("conString").ConnectionString

    Dim strQuery As [String] = "select ID, ContinentName from Continents"

    Dim con As New SqlConnection(strConnString)

    Dim cmd As New SqlCommand()

    cmd.CommandType = CommandType.Text

    cmd.CommandText = strQuery

    cmd.Connection = con

    Try

       con.Open()

       ddlContinents.DataSource = cmd.ExecuteReader()

       ddlContinents.DataTextField = "ContinentName"

       ddlContinents.DataValueField = "ID"

       ddlContinents.DataBind()

    Catch ex As Exception

       Throw ex

    Finally

       con.Close()

       con.Dispose()

    End Try

  End If

End Sub

 

 

Populating the Country DropDownList

Next on the SelectedIndexChanged Event of the parent Continent DropDownList I am populating the Countries DropDownList based on the ID of the Continent Selected by the user


C#

protected void ddlContinents_SelectedIndexChanged(object sender, EventArgs e)

{

    ddlCountry.Items.Clear();

    ddlCountry.Items.Add(new ListItem("--Select Country--", ""));

    ddlCity.Items.Clear();

    ddlCity.Items.Add(new ListItem("--Select City--", ""));   

 

    ddlCountry.AppendDataBoundItems = true;

    String strConnString = ConfigurationManager

        .ConnectionStrings["conString"].ConnectionString;

    String strQuery = "select ID, CountryName from Countries " +

                       "where ContinentID=@ContinentID";

    SqlConnection con = new SqlConnection(strConnString);

    SqlCommand cmd = new SqlCommand();

    cmd.Parameters.AddWithValue("@ContinentID",

        ddlContinents.SelectedItem.Value); 

    cmd.CommandType = CommandType.Text;

    cmd.CommandText = strQuery;

    cmd.Connection = con;

    try

    {

        con.Open();

        ddlCountry.DataSource = cmd.ExecuteReader();

        ddlCountry.DataTextField = "CountryName";

        ddlCountry.DataValueField = "ID";

        ddlCountry.DataBind();

        if (ddlCountry.Items.Count > 1)

        {

            ddlCountry.Enabled = true;

        }

        else

        {

            ddlCountry.Enabled = false;

            ddlCity.Enabled = false;

        }

    }

    catch (Exception ex)

    {

        throw ex;

    }

    finally

    {

        con.Close();

        con.Dispose();

    }

}

   

 

VB.Net

Protected Sub ddlContinents_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

   ddlCountry.Items.Clear()

   ddlCountry.Items.Add(New ListItem("--Select Country--", ""))

   ddlCity.Items.Clear()

   ddlCity.Items.Add(New ListItem("--Select City--", ""))

 

   ddlCountry.AppendDataBoundItems = True

   Dim strConnString As [String] = ConfigurationManager _

                   .ConnectionStrings("conString").ConnectionString

   Dim strQuery As [String] = "select ID, CountryName from Countries " _

                                    & "where ContinentID=@ContinentID"

   Dim con As New SqlConnection(strConnString)

   Dim cmd As New SqlCommand()

   cmd.Parameters.AddWithValue("@ContinentID", _

                             ddlContinents.SelectedItem.Value)

   cmd.CommandType = CommandType.Text

   cmd.CommandText = strQuery

   cmd.Connection = con

   Try

      con.Open()

      ddlCountry.DataSource = cmd.ExecuteReader()

      ddlCountry.DataTextField = "CountryName"

      ddlCountry.DataValueField = "ID"

      ddlCountry.DataBind()

      If ddlCountry.Items.Count > 1 Then

             ddlCountry.Enabled = True

      Else

             ddlCountry.Enabled = False

             ddlCity.Enabled = False

      End If

   Catch ex As Exception

      Throw ex

   Finally

       con.Close()

       con.Dispose()

   End Try

End Sub

 

You will notice I am passing the ID of the continent as parameter to the Query using SelectedItemValue property of the DropDownList thus the query returns the records (Countries) for that Continent ID which are then bind to the Country DropDownList

 

   

 

Populating the City DropDownList

Now on the selection of the Country I am filling the Cities for that country into the City DropDownList.

C#

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)

{

    ddlCity.Items.Clear();

    ddlCity.Items.Add(new ListItem("--Select City--", ""));

    ddlCity.AppendDataBoundItems = true;

    String strConnString = ConfigurationManager

               .ConnectionStrings["conString"].ConnectionString;

    String strQuery = "select ID, CityName from Cities " +

                                "where CountryID=@CountryID";

    SqlConnection con = new SqlConnection(strConnString);

    SqlCommand cmd = new SqlCommand();

    cmd.Parameters.AddWithValue("@CountryID",

                          ddlCountry.SelectedItem.Value);

    cmd.CommandType = CommandType.Text;

    cmd.CommandText = strQuery;

    cmd.Connection = con;

    try

    {

        con.Open();

        ddlCity.DataSource = cmd.ExecuteReader();

        ddlCity.DataTextField = "CityName";

        ddlCity.DataValueField = "ID";

        ddlCity.DataBind();

        if (ddlCity.Items.Count > 1)

        {

            ddlCity.Enabled = true;

        }

        else

        {

            ddlCity.Enabled = false;

        }

     

    }

    catch (Exception ex)

    {

        throw ex;

    }

    finally

    {

        con.Close();

        con.Dispose();

    }

}

 

 

 

VB.Net

Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

   ddlCity.Items.Clear()

   ddlCity.Items.Add(New ListItem("--Select City--", ""))

   ddlCity.AppendDataBoundItems = True

   Dim strConnString As [String] = ConfigurationManager _

                      .ConnectionStrings("conString").ConnectionString

   Dim strQuery As [String] = "select ID, CityName from Cities " _

                      & "where CountryID=@CountryID"

   Dim con As New SqlConnection(strConnString)

   Dim cmd As New SqlCommand()

   cmd.Parameters.AddWithValue("@CountryID", _

                               ddlCountry.SelectedItem.Value)

   cmd.CommandType = CommandType.Text

   cmd.CommandText = strQuery

   cmd.Connection = con

   Try

        con.Open()

        ddlCity.DataSource = cmd.ExecuteReader()

        ddlCity.DataTextField = "CityName"

        ddlCity.DataValueField = "ID"

        ddlCity.DataBind()

        If ddlCity.Items.Count > 1 Then

            ddlCity.Enabled = True

        Else

            ddlCity.Enabled = False

        End If

   Catch ex As Exception

        Throw ex

   Finally

         con.Close()

         con.Dispose()

   End Try

End Sub

 

Above I am firing a query on the Cities Table and getting all the cities that belong to that country which was selected by the user.

 

Displaying the Results

Finally on the SelectedIndexChanged event of the City DropDownList I am displaying the complete selections done by the user.

   

  

C#

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)

{

    lblResults.Text = "You Selected " +

                      ddlContinents.SelectedItem.Text + " -----> " +

                      ddlCountry.SelectedItem.Text + " -----> " +

                      ddlCity.SelectedItem.Text;

}

 

VB.Net

Protected Sub ddlCity_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

   lblResults.Text = "You Selected " & _

                     ddlContinents.SelectedItem.Text & " -----> " & _

                     ddlCountry.SelectedItem.Text & " -----> " & _

                     ddlCity.SelectedItem.Text

End Sub

 

The output is shown in the screenshot below


ScreenShot Displaying the working of Cascading DropDownLists

Thus we come to the end of this article. Download the sample source code in VB.Net and C# using the link below

CascadingDropDownLists.zip (130.31 kb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

vamsi said:
wowwThanq for keeping this code .......i worked on this example and got result...it will be very useful example for freshers....Thanq.keep uploading this type of examples.
January 28, 2010  

vamsi said:
String strQuery select ID CountryName from Countries br br where ContinentID@ContinentIDbr br is different from what u done in program.You removed that in ur downloaded program.This difference cost me 30 mins...Except dat everything was good.
February 01, 2010  

Mudassar Khan said:
Reply To: vamsi
Hi,
What was the issue you faced ?
February 01, 2010  

hina said:
Thank you for sharing this concept.Really it is good websitethx once again.This topic helped me out of the prblmworking fine. Please can u tel me how to refer to the other articles.br
February 19, 2010  

Albert said:
If I were using an Access database how could I modify the connection string and parameters in the SelectedIndexChanged subs Can you please provide an example Thanks.
March 19, 2010  

Mudassar Khan said:
Reply To: Albert
Sorry at the moment I don't have it.Please post your question on asp.net forums
March 22, 2010  

mohamed said:
Cant restore your the CascadingDDL.bakbr br How Can I fix it
May 05, 2010  

Mudassar Khan said:
Reply To: mohamed
What is the error you are getting?
May 07, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code