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

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

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

Pandoh kishan said...

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

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

ANIL BABU Mandla 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..

Dharmapriya Mohanty 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

sri Harsha said...

nice

firoz said...

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

dheena ram 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

Avinash Yadav said...

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

rashed bin hares said...

very nice.

Avil Anil 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

Sandeep Kr. Mishra 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?

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

Krishna Mistry said...

thanks,it works very well

Give your Valuable Comments

Other Related Posts

© 2010-2012 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.