imaco imaco - 1 year ago 55
ASP.NET (C#) Question

ASP.NET filtering dropdownlist basing on a previous one

Let's say I have 2 tables:


|country| id_country |
|------- | ---------- |
|USA | 1 |
|England | 2 |

b) table B

city | id_country
---------- | ----------
NY | 1
LA | 1
London | 2
Manchester | 2

Obviously if I chose USA the second dropdownlist should show NY and LA, but I don't know how to store a parametr of first dropdownlist. The code that filters second dropdownlist should probably look like this:

A, B
B.id_country = X

And the x is parametr of firstdropdownlist (A.id_country), any ideas that would solve my problem?

Answer Source

bind first dropdown list with id_country as value member and country as display member. set AutoPostBack property of fist dropdown as true. add selected index change event to the first dropdown( double click dropdown on design view). on selected index changed event you can load the second dropdown.

select city, id_country from B where id_country = @id_country

set id_country parameter from first dropdown SelectedValue, set the second dropdown data source, display and value members and finally call DataBind() of second dropdown

check Creating Cascading DropDownLists in ASP.Net if you need complete tutorial or you can try AJAX Cascading DropDownList with data load using web service methods without full page poastback