Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Populate One Asp.net Dropdown based on Selection in Another Dropdown

Oct 31, 2010
Introduction

Here I will explain how to populate one dropdown based on selection in another dropdown asp.net using c#.

Description

I have three dropdowns Country dropwdown, State dropdown, Region dropdown I need to populate states dropdown based on country dropdown and I need to populate region dropdown based on states dropdown for that what we have to do first design three tables in sql server with data like this 

CountryTable 

StateTable

RegionTable

After that design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CasCading Dropdowns Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Select Country:
</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
Select State:
</td>
<td>
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlState_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
Select Region:
</td>
<td>
<asp:DropDownList ID="ddlRegion" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

In code behind write like this 


private String strConnection = "Data Source=XZCBJ017550;Initial Catalog=MySamplesDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindContrydropdown();
}

}
/// <summary>
/// Bind COuntrydropdown
/// </summary>
protected void BindContrydropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from CountryTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlCountry.DataSource = ds;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryID";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("--Select--", "0"));
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));

}
/// <summary>
/// Bind State Dropdown Based on CountryID
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int CountryID = Convert.ToInt32(ddlCountry.SelectedValue);
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from StateTable where CountryID="+CountryID, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlState.DataSource = ds;
ddlState.DataTextField = "StateName";
ddlState.DataValueField = "StateID";
ddlState.DataBind();
ddlState.Items.Insert(0, new ListItem("--Select--", "0"));
if(ddlState.SelectedValue=="0")
{
ddlRegion.Items.Clear();
ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));
}

}
/// <summary>
/// Bind Region dropdown based on Re
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
int StateID = Convert.ToInt32(ddlState.SelectedValue);
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select * from RegionTable where StateID=" + StateID, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlRegion.DataSource = ds;
ddlRegion.DataTextField = "RegionName";
ddlRegion.DataValueField = "RegionID";
ddlRegion.DataBind();
ddlRegion.Items.Insert(0, new ListItem("--Select--", "0"));
}
Demo



DownLoad Attached Sample here


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

61 comments :

Anonymous said...

GREAT WORK.. WAS LOOKING FOR THIS FOR 2 DAYS

Anonymous said...

very well done boss...
It is very help full for me...

thanks.....

Anonymous said...

Please can u do exactly the same work without a postback to the web server.

Pratap Kumar said...

hi , can u please provide the validations for the above code

Anonymous said...

I love you!!!!!!!!!!!!!!!!!!

Anonymous said...

nice

Shyam Kishore said...

great work in simplified way

Kishan Thakur(Pandoh)Mandi said...

please suresh ji post with latest technology like mvc,linq,silverlight and more sharepoints
thanks for all posts
kishanthakur

Unknown said...

this is best example i ever seen in any website , with such compact details.. i loved it..
thanks

Anonymous said...

Sir its Working, But when i click on "--submit--" its shows an exception "Input string was not in a correct format."
help me.

Anonymous said...

its displaying error like "both datasource and datasource id are same remove one thing".

Anonymous said...

very helpful.....................
plz help me out how to put a primary key and foreign to thse tables in the above example......

Help said...

I have one requirement
Drop down list to choose types: NFC/RFID reader
when user choose reader show description in Label

Description for RFID Reader : Reading range 6-12 Meteres.

Description for NFC Reader : Reading Range 3-5 mm.

akhil said...

HELPED A LOT...MY HEARTFULL THANKS TO U SURESH BHAI..

Unknown said...

sir ,
ist many many thanks to u.
this is very useful for my project

AllBhktiSongs said...

thanks sir

Anonymous said...

Really Enjoy ....Great Work!!

chandana said...

Sir pls post article for website live chat concept.
and also please give code to display the list of members in online for chat. really it will be helpful if you post this for us

Shriya said...
This comment has been removed by the author.
Shriya said...

changes are not reflecting in the second drop down

Unknown said...

nice

Naat Khan said...

suresh bhai ki jai..........

Unknown said...

thanxs alot..
This coding is really useful for me and my friends

thanxs na

Anonymous said...

gud work dude...keep it up !!

Muthu Kumar said...

It's very useful to me... Thankz boss

Anonymous said...

Hey Andhra Paris..

Love you so........much.

Anonymous said...

Hi, I am getting these errors (for every occurence of ddlCountry, ddlState, ddlRegion and
SqlConnection(strConnection))please help me to solve..
1)The name 'ddlCountry' does not exist in the current context

2)The name 'ddlState' does not exist in the current context

3)The name 'ddlRegion' does not exist in the current context

4)The best overloaded method match for 'System.Data.SqlClient.SqlConnection.SqlConnection(string)' has some invalid arguments

5)Argument 1: cannot convert from 'System.Data.SqlClient.SqlConnection' to 'string'

Purav12 said...

oh once again in the end i got solution from this site only... thanks a lot.. mr.suresh

Anonymous said...

So simple and clearly explained

Anonymous said...

Great work Mr. Suresh!

What exactly do you mean "In code behind write like this.."? And, how does a Newbie like me take advantage of that code and make it executable?

What file must I create to bring the code home?

Help!

Gerard

Anonymous said...

Hello,

Your code is simple and easy to understand thank u
but can i knw can we bind these dropdownlist without using the concept of primary and foreign key.
Is there any code which can be done through front end.

Regards
Anni

Anonymous said...

Sir grt8 artical but can pls tell me what changes i have do when i am having all the 3 dropdownlist in same update panel.And on selection of country from ddl state ddl should get change.

regards
pranjal

Anonymous said...

Thank you soo much,.,..!!!

Anonymous said...

gertgdf

hasib Zuhoor said...

Dear Friends I need this the same cascading menu but the source code in three tier archetichure. thanks

Unknown said...

plz tell me difference between selectedvalue,selectedindexchange,selecteditem.value with example

Unknown said...

Sir could you please help me with the code how to populate datas in to a textbox based on dropdown selected value from database

Unknown said...

2nd dropdown not showing the state..

Anonymous said...

getting error at
throw new NotImplementedException();
as
The method or operation is not implemented.
how can i solve plz reply

Anonymous said...

sir I need your help....

I have a GridView that contains 2 columns each containing dropdownlist. If I select any value in 1st dropdown list I should get the respective values in other dropdownlist and not all values....

for example I made 2 columns category and name

category >>>><<<< name

fruit >>>><<<< mango
vegetable >>>><<<< cabbage
vegetable >>>><<<< lauki
fruit >>>><<<< grapes


Thanks..

Anonymous said...

can you make the same thing working in a grid view? any replies will be welcomed

Mayank Vagh said...

brilliant post,
it is possible to show this data in gridview?

Anonymous said...

hi suresh really u r doing a wonderful job...daily am using ur examples they are very helpful to me my heartfully am appreciating u my dear thanks a lotttttt.....

Anonymous said...

Hello Mr Suresh.. Many Many thanks for this valuable post... Sorry to say that ,, I have a doubt on this... Can we do the same with help of Ajax??because making autopostback true will refresh the whole page every time we change any value.. Can we use ajax in anyway to partially refresh the page and retrive value???

Waiting for your valuable reply...
Thank you....

Anonymous said...

GUD

Anonymous said...

I wouldnt use concatenation in sqlcommand.I wuld rather use a stored procedure. Your code is prone to SqlInjection.Good job though.

Unknown said...

thanks,it works very well

chaitanya said...

thankyou boss.its very helpful.it look like simple manner

Anonymous said...

can any one show me the example of "load cascading dropdownlist items on gridview Edit mode "

Unknown said...

iv been doing this with tutorials and examples for weeks now..and this morning i came across this thread and guess what my project is done...

thank u suresh
*Victory dance*

Unknown said...

Hi Suresh,
aspdotnet-suresh web sit is very helpful .
Could you pls tell me how get the all Country names and state names without database support.

Thanks for sharing your valuable infomation.................

Unknown said...

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindContrydropdown();
}
}

// Use above code in page load for avoid page reloaded for every submition

Unknown said...

your coding style is very simple and easy. you are a great man of Microsoft .Net

Vishu said...

sir,
explain this but with out DATABASE

Anonymous said...

can i have this code in VB.NET

Anonymous said...

some time when i click on dropdownlist select any one of the option than my coloum name of grid is invisible after click on dropdown nd some time its visible.....sometimes my coloum name of gridview is visible when i select the option from dropdown...so if anyone know why this happend than please tell me........

Unknown said...

how to use this program in three tier architecture .plz send me code

Unknown said...

object reference not set to an instance of an object exception error
what the solution

Unknown said...

Thank you...!!!
its very simple code

.NET said...

Thanks Sir...

Unknown said...

Your coding is very nice sir,i want coding,if i select dropdown list in mobile number that details show text bos

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.