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
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. |
|||
|
|||
61 comments :
GREAT WORK.. WAS LOOKING FOR THIS FOR 2 DAYS
very well done boss...
It is very help full for me...
thanks.....
Please can u do exactly the same work without a postback to the web server.
hi , can u please provide the validations for the above code
I love you!!!!!!!!!!!!!!!!!!
nice
great work in simplified way
please suresh ji post with latest technology like mvc,linq,silverlight and more sharepoints
thanks for all posts
kishanthakur
this is best example i ever seen in any website , with such compact details.. i loved it..
thanks
Sir its Working, But when i click on "--submit--" its shows an exception "Input string was not in a correct format."
help me.
its displaying error like "both datasource and datasource id are same remove one thing".
very helpful.....................
plz help me out how to put a primary key and foreign to thse tables in the above example......
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.
HELPED A LOT...MY HEARTFULL THANKS TO U SURESH BHAI..
sir ,
ist many many thanks to u.
this is very useful for my project
thanks sir
Really Enjoy ....Great Work!!
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
changes are not reflecting in the second drop down
nice
suresh bhai ki jai..........
thanxs alot..
This coding is really useful for me and my friends
thanxs na
gud work dude...keep it up !!
It's very useful to me... Thankz boss
Hey Andhra Paris..
Love you so........much.
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'
oh once again in the end i got solution from this site only... thanks a lot.. mr.suresh
So simple and clearly explained
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
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
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
Thank you soo much,.,..!!!
gertgdf
Dear Friends I need this the same cascading menu but the source code in three tier archetichure. thanks
plz tell me difference between selectedvalue,selectedindexchange,selecteditem.value with example
Sir could you please help me with the code how to populate datas in to a textbox based on dropdown selected value from database
2nd dropdown not showing the state..
getting error at
throw new NotImplementedException();
as
The method or operation is not implemented.
how can i solve plz reply
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..
can you make the same thing working in a grid view? any replies will be welcomed
brilliant post,
it is possible to show this data in gridview?
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.....
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....
GUD
I wouldnt use concatenation in sqlcommand.I wuld rather use a stored procedure. Your code is prone to SqlInjection.Good job though.
thanks,it works very well
thankyou boss.its very helpful.it look like simple manner
can any one show me the example of "load cascading dropdownlist items on gridview Edit mode "
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*
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.................
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindContrydropdown();
}
}
// Use above code in page load for avoid page reloaded for every submition
your coding style is very simple and easy. you are a great man of Microsoft .Net
sir,
explain this but with out DATABASE
can i have this code in VB.NET
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........
how to use this program in three tier architecture .plz send me code
object reference not set to an instance of an object exception error
what the solution
Thank you...!!!
its very simple code
Thanks Sir...
Your coding is very nice sir,i want coding,if i select dropdown list in mobile number that details show text bos
Note: Only a member of this blog may post a comment.