Clairooo
Clairooo

Reputation: 1

Filter options of one SELECT control according to another SELECT control options with asp.net

I have two select controls . the first one contains names of countries and the another one contains cities names . I need to make the second one display names of the cities of selected country from the first one.

Upvotes: 0

Views: 191

Answers (2)

CAbbott
CAbbott

Reputation: 8098

You didn't specify how you wanted to accomplish it (postback vs. ajax), so, I picked postback.

  1. Create a DropDownList control for countries (in my example it's ddlCountries)
  2. Bind the list of countries to it - probably in Page_Load wrapped in an if (!Page.IsPostback)
  3. Double-click on the SelectedIndexChanged event to create a handler for that event.

Then handle the SelectedIndexChanged event on the DropDownList control for country and set the DropDownList for cities (untested example):

Protected void ddlCountries_SelectedIndexChanged(object sender, System.EventArgs e)
{
    // Get the list of cities for the selected country 
    // using ddlCountries.SelectedItem.Value;
    ddlCities.DataSource = GetCities(ddlCountries.SelectedItem.Value);
    ddlCities.DataTextField="CityName";
    ddlCities.DataValueField="CityName";
    ddlCities.DataBind();
}

Upvotes: 1

RBZ
RBZ

Reputation: 2074

The simplest solution would be on country selection:

var citiesToDisplay = Cities.Where(city=> city.CountryId == selectedCountryId);

Upvotes: 0

Related Questions