Populate Cascading DropDownList On Selection ASP.NET

Populate Cascading DropDownList In Asp.Net C# VB.NET Based On Selection Of Other DropDown In SelectedIndexChanged Event. binding state DropDown based on selection of Country DropDownlist and then populating Cities on selection of State.

There are several situations where we need to populate second or third dropdownlist list based on selection of first or second dropdwonlist in asp.net.

populate dropdown based on selection in SelectedIndexChanged Event asp.net
For this we need to write code in code behind in the SelectedIndexChanged Event of respective Dropdownlist to implement the cascading of DropDowns.

HTML SOURCE OF PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <table><tr>
   4:  <td><strong>Country :</strong></td>
   5:  <td><asp:DropDownList ID="ddlCountry" runat="server"
   6:                        AutoPostBack="True" 
   7:                        onselectedindexchanged=
   8:                   "ddlCountry_SelectedIndexChanged">
   9:      </asp:DropDownList>
  10:  </td>
  11:   
  12:  <td><strong>State:</strong></td>
  13:  <td><asp:DropDownList ID="ddlState" runat="server" 
  14:                        AutoPostBack="True" 
  15:                        onselectedindexchanged=
  16:                   "ddlState_SelectedIndexChanged">
  17:      </asp:DropDownList></td>
  18:   
  19:  <td><strong>City:</strong></td>
  20:  <td><asp:DropDownList ID="ddlCity" runat="server" 
  21:                        AutoPostBack="True">
  22:      </asp:DropDownList></td>
  23:  </tr>
  24:  <tr><td><asp:Label ID="lblMsg" runat="server">
  25:         </asp:Label>
  26:      </td>
  27:  </tr>  
  28:  </table>
  29:   </div>
  30:   </form>

Write following code in respective events of page and dropdownlists.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillCountry();
        }
    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        int CountryID = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
        FillStates(CountryID);
        ddlCity.SelectedIndex = 0;
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        int StateID = Convert.ToInt32(ddlState.SelectedValue.ToString());
        FillCities(StateID);
    }

    private void FillCountry()
    {
        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT CountryID, CountryName FROM Country";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        if (objDs.Tables[0].Rows.Count > 0)
        {
            ddlCountry.DataSource = objDs.Tables[0];
            ddlCountry.DataTextField = "CountryName";
            ddlCountry.DataValueField = "CountryID";
            ddlCountry.DataBind();
            ddlCountry.Items.Insert(0, "--Select--");
        }
        else
        {
            lblMsg.Text = "No Countries found";
        }
    }

    private void FillStates(int countryID)
    {
        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID";
        cmd.Parameters.AddWithValue("@CountryID", countryID);
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        if (objDs.Tables[0].Rows.Count > 0)
        {
            ddlState.DataSource = objDs.Tables[0];
            ddlState.DataTextField = "StateName";
            ddlState.DataValueField = "StateID";
            ddlState.DataBind();
            ddlState.Items.Insert(0, "--Select--");
        }
        else
        {
            lblMsg.Text = "No states found";
        }
    }

    private void FillCities(int stateID)
    {
        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID";
        cmd.Parameters.AddWithValue("@StateID", stateID);
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        if (objDs.Tables[0].Rows.Count > 0)
        {
            ddlCity.DataSource = objDs.Tables[0];
            ddlCity.DataTextField = "CityName";
            ddlCity.DataValueField = "CItyID";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "--Select--");
        }
        else
        {
            lblMsg.Text = "No Cities found";
        }
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  FillCountry()
 End If
End Sub
Protected Sub ddlCountry_SelectedIndexChanged(sender As Object, e As EventArgs)
 Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
 FillStates(CountryID)
 ddlCity.SelectedIndex = 0
End Sub
Protected Sub ddlState_SelectedIndexChanged(sender As Object, e As EventArgs)
 Dim StateID As Integer = Convert.ToInt32(ddlState.SelectedValue.ToString())
 FillCities(StateID)
End Sub

Private Sub FillCountry()
 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT CountryID, CountryName FROM Country"
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 If objDs.Tables(0).Rows.Count > 0 Then
  ddlCountry.DataSource = objDs.Tables(0)
  ddlCountry.DataTextField = "CountryName"
  ddlCountry.DataValueField = "CountryID"
  ddlCountry.DataBind()
  ddlCountry.Items.Insert(0, "--Select--")
 Else
  lblMsg.Text = "No Countries found"
 End If
End Sub

Private Sub FillStates(countryID As Integer)
 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"
 cmd.Parameters.AddWithValue("@CountryID", countryID)
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 If objDs.Tables(0).Rows.Count > 0 Then
  ddlState.DataSource = objDs.Tables(0)
  ddlState.DataTextField = "StateName"
  ddlState.DataValueField = "StateID"
  ddlState.DataBind()
  ddlState.Items.Insert(0, "--Select--")
 Else
  lblMsg.Text = "No states found"
 End If
End Sub

Private Sub FillCities(stateID As Integer)
 Dim strConn As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim con As New SqlConnection(strConn)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"
 cmd.Parameters.AddWithValue("@StateID", stateID)
 Dim objDs As New DataSet()
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 con.Open()
 dAdapter.Fill(objDs)
 con.Close()
 If objDs.Tables(0).Rows.Count > 0 Then
  ddlCity.DataSource = objDs.Tables(0)
  ddlCity.DataTextField = "CityName"
  ddlCity.DataValueField = "CItyID"
  ddlCity.DataBind()
  ddlCity.Items.Insert(0, "--Select--")
 Else
  lblMsg.Text = "No Cities found"
 End If
End Sub

Build and run the code.

Download Sample Code



30 comments:

  1. That was simply great , Ankit Jain .

    More Interesting to read even.

    ReplyDelete
  2. Hi Abhay, thanks for te feedback :)

    btw i am amit not ankit

    ReplyDelete
  3. Its really working...
    Great job...
    and thanks
    it helped me in my project

    ReplyDelete
  4. That very nice, a demo will be even better

    ReplyDelete
  5. How should i implement if web service is located at another location..i tried by giving the path of the webservice

    ReplyDelete
  6. Thankyou soooooooooooo much...

    From Tanisha Sayyad

    ReplyDelete
  7. venky

    thank u sooooooooooooooooooooooooooooooooooo
    muuuuuuuuuuuuuuuuucccccccccccccchhhhhhhhhhhhhhhhhhh

    ReplyDelete
  8. nice article.

    god bless you.

    Juan Alberto Patal

    ReplyDelete
  9. This is a nice example. I wonder if an user wants to update the row n the gridview, what should do? Is it possible for you to explain or show the code? Thanks

    ReplyDelete
  10. Hi, just want to ask how can i handle the exception of "Input string was not in a correct format." when i go back and select the --Select-- or the value 0??? please advise.

    ReplyDelete
  11. finally got a complete code..........thank u so much.

    ReplyDelete
  12. u r tutorial is really good

    i m using this same in my project but in that i m finding some problem like

    when 1st time i select country all ddl work in proper way,but if i select Country ddl again to change other country than at that time state ddl is showing -select state- twice and same is case with city ddl

    ReplyDelete
  13. @Above: I have attached source code in the post, download and run it, let me know if you still have any errors ?

    ReplyDelete
  14. Where do you get the Database ...?

    ReplyDelete
  15. Database is included in sample code

    ReplyDelete
  16. superb and thanks really.i need this in my project.

    ReplyDelete
  17. i have an error saying that
    "Input string was not in a correct format."

    i have change the datatype of my countryID and other ID's in my database from int to varchar..

    i think this line affects it..
    int CountryID = Convert.ToInt32(ddlCountry.SelectedValue.ToString());

    what should be the alternative code if im using varchar as datatype not int..?

    i hope u got my question.. sorry for my bad english.. thanks in advance..

    ReplyDelete
  18. @Above : Change your code as mentioned below

    string CountryID = ddlCountry.SelectedValue.ToString();

    and change methods FillStates, and FillCities as follows

    private void FillStates(string countryID)

    ReplyDelete
  19. I havent ran it yet for myself, but thank you soooo much....I have been screaching the web for weeks trying to figure out how to get my dropdownlist controls to work...I am really gratful for you taking the time out and helping...again thank you so much
    -Crystal

    ReplyDelete
  20. I haven't tried your code yet 'cause I've been looking for a solution to this problem for quite a long time now and I'm really tired (2:27 AM). However, I must say that I think it's the right way to do this just by scrolling through it (seems to solve the general ddl -> ddl2 problem covering selections from the database, not just particular cases). Thanks in advance for this great post.

    ReplyDelete
  21. thnx... it was really useful...

    ReplyDelete
  22. hi it is really working and its help in my project how to i stored in database???plz give me code that

    ReplyDelete
  23. Helped out so much!

    ReplyDelete
  24. I am trying to use the VB.NET code to populate State, County and City. I have the connection string pointing to a SQL Database. If I change the connection string, DDL names, and Protected Voids/Private Voids, in your C# it works. However, in VB when I view it on the web the drop downs do not populate. They are blank and very small.

    I can post code if need be. Thanks so much!

    ReplyDelete
  25. Thank You so Much sir....this is very helpful for me.

    ReplyDelete
  26. Hi Amit, Thank you for your code, I haven't run it yet, but i think this would refresh the page at every selection on the Dropdown list, right?

    ReplyDelete