SIGN UP MEMBER LOGIN:    
ARTICLE

DropDownList with country, state and city in ASP. NET

Posted by Rohatash Kumar Articles | ASP.NET Programming September 13, 2011
This article shows when you select a country then its automatically shows the states name of that country in next DropDownList. Then when you select a state, the cities DropDownList will fetch the related cities for that state.
Reader Level:
Download Files:
 

This article shows how to create three DropDownList to display countries, states and cities. When you select a country then its automatically shows the states name of that country in next DropDownList. Then when you select a state, the cities DropDownList will fetch the related cities for that state.

Creating table for country, state and city.

Country Table

Create Table Country

(

CountryId Int Primary Key,

County Varchar(30)

)

Countrystate Table

Create Table countryState

(

StateId Int Primary Key,

CountryId Int Foreign Key References Country(CountryId),

State Varchar(30)

)

StateCity Table

Create Table stateCity

(

CityId Int,

StateId Int Foreign Key References countryState(StateId),

City Varchar(30)

)

Now insert values in the table.

Insert Into Country Values(101,'India')

Insert Into Country Values(102,'USA')

Insert Into Country Values(103,'Pakistan')

 

Insert Into countryState Values(1001,101,'U.P')

Insert Into countryState Values(1002,101,'Kerala')

Insert Into countryState Values(1003,101,'Kasmir')

Insert Into countryState Values(2001,102,'Colorado')

Insert Into countryState Values(2002,102,'Delaware')

Insert Into countryState Values(2003,102,'Georgia')

Insert Into countryState Values(3001,103,'Punjap')

Insert Into countryState Values(3002,103,'Baluchistan')

Insert Into countryState Values(3003,103,'Sind')

 

Insert Into stateCity Values(11,1001,'Kanpur')

Insert Into stateCity Values(12,1001,'Dg')

Insert Into stateCity Values(21,1002,'Pal')

Insert Into stateCity Values(22,1002,'Tri')

Insert Into stateCity Values(31,1003,'Jammu')

Insert Into stateCity Values(32,1003,'Manali')

Insert Into stateCity Values(41,2001,'Alabama')

Insert Into stateCity Values(42,2001,'Arizona')

Insert Into stateCity Values(51,2002,'Bellefonte')

Insert Into stateCity Values(52,2002,'Felton')

Insert Into stateCity Values(61,2003,'Rustavi')

Insert Into stateCity Values(62,2003,'Kobulati')

Insert Into stateCity Values(71,3001,'Lahore')

Insert Into stateCity Values(72,3001,'Faisalabad')

Insert Into stateCity Values(81,3002,'Quetta')

Insert Into stateCity Values(82,3002,'Nasirabad')

Insert Into stateCity Values(91,3003,'Krachi')

Insert Into stateCity Values(92,3003,'Mirpur khas')

Now select it.

select * from Country;


countrytable.gif


Countrytable

 

select * from  countryState;


citytable.gif


Statetable

 

select * from stateCity;


statetable.gif


Citytable

Now drag and drop three DropDownList to display countries, states and cities and three update panel control on the page.

fig1.gif
 

Figure1

.aspx code

<head runat="server">

   <title></title>

</head>

<body>

   <form id="form1" runat="server">

  <asp:ScriptManager ID="ScriptManager1" runat="server">

   </asp:ScriptManager>

   <div>

       <asp:UpdatePanel ID="countrypanel" runat="server">

          <ContentTemplate >

              <span class="style1"><strong>Select Country:</strong></span>

             <asp:DropDownList ID="ddlcountry" AutoPostBack ="true" AppendDataBoundItems

="true" runat="server" Height="20px" Width="156px"   

onselectedindexchanged="ddlcountry_SelectedIndexChanged" BackColor="#3399FF"

                  ForeColor="#FF9999">

           </asp:DropDownList>

       </ContentTemplate>

 

     <Triggers>

      <asp:AsyncPostBackTrigger ControlID ="ddlcountry" />

     </Triggers>

  </asp:UpdatePanel>

       <br />

 

 <asp:UpdatePanel ID="statepanel" runat="server">    

    <ContentTemplate >

        <span class="style1"><strong>&nbsp;&nbsp;&nbsp;&nbsp; Select State:</strong></span>

      <asp:DropDownList ID="ddlstate" AutoPostBack ="true"

       AppendDataBoundItems ="true"  runat="server" Height="20px"

Width="155px"               onselectedindexchanged="ddlstate_SelectedIndexChanged"

            BackColor="#FF3399" ForeColor="Maroon">

      </asp:DropDownList>

    </ContentTemplate>

    <Triggers >

       <asp:AsyncPostBackTrigger ControlID ="ddlstate" />

       </Triggers>

    </asp:UpdatePanel>

       <br />

 

<asp:UpdatePanel ID="citypanel" runat="server">     

   <ContentTemplate >      

       <span class="style1"><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Select City:</strong></span>      

     <asp:DropDownList ID="ddlcity" AutoPostBack ="true"

   AppendDataBoundItems ="true" runat="server" Height="20px" Width="155px"

           BackColor="#66FFFF" ForeColor="#006666">

     </asp:DropDownList>

  </ContentTemplate>

  <Triggers >

    <asp:AsyncPostBackTrigger ControlID ="ddlcity" />         </Triggers>  

 </asp:UpdatePanel>

 </div>

   </form>

</body>

</html>

 

.VB code

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

 

namespace CountryStateCity

{

   public partial class WebForm1 : System.Web.UI.Page

    {

       private SqlConnection conn = new SqlConnection("Data source=.; uid=sa;   pwd=Password$2; database=CountryStateCity");

 

       public void Bind_ddlCountry()

        {

            conn.Open();

           SqlCommand cmd =new SqlCommand("select County,CountryId from Country", conn);

           SqlDataReader dr = cmd.ExecuteReader(); 

            ddlcountry.DataSource = dr;

            ddlcountry.Items.Clear();

            ddlcountry.Items.Add("--Please Select country--"); 

            ddlcountry.DataTextField = "County"

            ddlcountry.DataValueField = "CountryId";

            ddlcountry.DataBind();

            conn.Close();

        }

       public void Bind_ddlState()

        {

            conn.Open();

 

           SqlCommand cmd =new SqlCommand("select State,StateID from countryState where CountryId='" + ddlcountry.SelectedValue +"'", conn);

 

           SqlDataReader dr = cmd.ExecuteReader();

             ddlstate.DataSource = dr;

            ddlstate.Items.Clear(); 

            ddlstate.Items.Add("--Please Select state--");

            ddlstate.DataTextField = "State";

            ddlstate.DataValueField = "StateID";

          ddlstate.DataBind();

            conn.Close();

        }

       public void Bind_ddlCity()

        {

            conn.Open();

            SqlCommand cmd =new SqlCommand("select * from stateCity where StateId ='" + ddlstate.SelectedValue +"'", conn);

 

           SqlDataReader dr = cmd.ExecuteReader();

            ddlcity.DataSource = dr;

            ddlcity.Items.Clear();

            ddlcity.Items.Add("--Please Select city--");

            ddlcity.DataTextField = "City";

            ddlcity.DataValueField = "CityID";
            ddlcity.DataBind();

             conn.Close();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind_ddlCountry();
            }
        }
        protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_ddlState();
        }
        protected void ddlstate_SelectedIndexChanged(object sender, EventArgs e)
        {

           Bind_ddlCity();

      }

   }

 }

 

 

Now run the application and test it.
 

fig2.gif
 

 

Figure2

 

Now select a country, then its automatically shows the states name of that country in next DropDownList. For example we select USA.
 

fig3.gif
 

Figure3

 

Now select a State, then its automatically shows the cities name of that state in next DropDownList. For example we select Punjab.
 

fig4.gif

 

Figure4
 

Note: You can see a demo of this article by downloading this application.

 

Login to add your contents and source code to this article
share this article :
post comment
 

sir, that pgm is written above is not working properly..

Posted by sahil chhabra Dec 08, 2011

You can also use the AJAX CascadingDropDown control: http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx

Posted by David Ribeiro Oct 27, 2011

I recommend you to use Firebug, with network option. Monitorize the posts on "Network" tab, and you will see that my solution will have _ASYNCPOST as true!

Posted by David Ribeiro Oct 27, 2011

This is a common scenario on the real world, however, consider these two tips: a) You only need an update panel where there is information to update (do you need to update anything on countrypanel?) b) You need specific controls to update other controls (you change a value on one DropDownList, it affects the datasource of another). So, why do you put an update panel on all DropDownLists and allow child to act as triggers? Your idea is great and happens a lot, but it doesn't solve itself just by wrapping DropDownLists inside an update panel! So, being concrete: 1. You don't need countrypanel - there won't be any update to its contents, so no need to update it 2. On statepanel, you should apply childactastriggers to false, updatemode to conditional, and apply asyncpostback to ddlcountry SelectedIndexChanged method 3. On citypanel, you should apply childactastriggers to false, updatemode to conditional, and apply asyncpostback to ddlstate SelectedIndexChanged method This is the correct way to use update panels (I had these issues like... a lot!)

Posted by David Ribeiro Oct 27, 2011

Good

Posted by Pradip Pandey Sep 23, 2011
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor