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



If you like this post than join us or share

30 comments:

Abhay Goyal said...

That was simply great , Ankit Jain .

More Interesting to read even.


Unknown said...

Hi Abhay, thanks for te feedback :)

btw i am amit not ankit


Snehal Agrawal said...

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


Anonymous said...

That very nice, a demo will be even better


Naresh Ambati said...

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


Developers Code said...

thankyou very much.......


Developers Code said...

Thankyou soooooooooooo much...

From Tanisha Sayyad


venky said...

venky

thank u sooooooooooooooooooooooooooooooooooo
muuuuuuuuuuuuuuuuucccccccccccccchhhhhhhhhhhhhhhhhhh


Anonymous said...

nice article.

god bless you.

Juan Alberto Patal


Cats said...

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


Micheal said...

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.


Anonymous said...

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


Anonymous said...

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


Unknown said...

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


Anonymous said...

Where do you get the Database ...?


Unknown said...

Database is included in sample code


Anonymous said...

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


Anonymous said...

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..


Unknown said...

@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)


Anonymous said...

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


Anonymous said...

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.


Anonymous said...

thnx... it was really useful...


vatsal said...

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


Unknown said...

@vatsal: please refer Ajax cascading dropdownlist in gridview


Anonymous said...

Helped out so much!


Unknown said...

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!


Yii2 Framework said...

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


Yii2 Framework said...

thank u sir...ur grt.


Unknown said...

same task i want in gridview


Unknown said...

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?


Find More Articles