popuating values in one drop down list based on items in another dropdown list

Posted by Shailu_rajupate under C# on 5/12/2009 | Views : 2487 | Status : [Member] | Replies : 4
popuating values in one drop down list based on items in another dropdown list

base on selected state display values in city




Responses

Posted by: Syedshakeer on: 5/12/2009 [Member] Starter

Up
0
Down
Hi

First Create a Table with a Name States .It contains two columns as stateid and statename
stateid statename
----------------------
1 Andhra Pradesh
2 Karnataka
3 Maharastra


Next Create Another table with a name citys .It contains stateid and cityname columns.

stateid cityname
-------------------------
1 Hyderabad
2 Banglore
3 Mumbai



Drag and Drop Two Dropdownlist.
In first DropdownList retrive the data from a table states as follows

write in PageLoed Event:
SqlCommand cmd=new SqlCommand("select * from states",conn);
SqlDataReader reader=cmd.ExecuteReader();
DropDownList1.Items.Cleer();
while(reader.Read())
{
ListItem li=new ListItem();
li.Value=reader["stateid"];
li.Text=reader["statename"];
DropDownList1.Items.Add(li);

}


When you select a State the following Capital citys have to display in second dropdownlist2
so Doubleclik on DropdownList1 and write the below code:

SqlCommand conn=new SqlCommand("your connection");
conn2.Open();
SqlCommand cmd2=new SqlCommand("select * from citys where stateid="+ DropdownList1.SelectedValue+",conn2);
SqlDataReader reader2=cmd2.ExecuteReader();
DropDownList2.Items.Clear();
while(reader2.Read())
{
ListItem li2=new ListItem();
li2.Value=reader2["stateid"];
li2.Text=reader2["cityname"];
DropDownList2.Items.Add(li2);

}



Syed Shakeer Hussain

Shailu_rajupate, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vuyiswamb on: 5/12/2009 [Member] [MVP] [Administrator] NotApplicable

Up
0
Down
Good Morning Syedshakeer

A Very Good Answer Always advice people to use parameterized queries.

Keep up the good work.


Vuyiswa Maseko

Thank you for posting at Dotnetfunda
[Administrator]

Shailu_rajupate, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Neeks on: 5/13/2009 [Member] Bronze

Up
0
Down
Please use field names instead of *.
You can write select countryId, countryName from Country

Shailu_rajupate, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vuyiswamb on: 5/13/2009 [Member] [MVP] [Administrator] NotApplicable

Up
0
Down
Good Morning

Neeks that is Good , because it will make the query more faster. but i think he used a (*) just because he is doing an example to Shailu_rajupate.

Thank you for Posting at Dotnetfunda



Vuyiswa Maseko

Thank you for posting at Dotnetfunda
[Administrator]

Shailu_rajupate, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response