Simple cascading DropDownLists in ASP.NET

A popular requirement for a page is to have a cascade-type filter using DropDownLists. For example:

Country: [list of all countries you support]
City: [list of all cities with your shops in the SELECTED country]
Store: [all stores in the select city]

The obvious solution is to use:

Everything is well and good. The problem, however, is that the ControlParameter doesn’t work in chain (cascade). Using our previous example we have such control relationship: Country <- City <- Store; where <- denotes dependency. Assume that the user chooses the country “France”. What we expect, is that both the city and store will be updated accordingly. The result is as follows:

Country: France
City: Paris
Shop: Store A at 52 Wall Street (!)

All the solutions that I was able to found on the internet were neither short and all of them suggested use of AJAX. I don’t have anything against AJAX but I don’t see a reason to implement something that I don’t really need.

After playing around for a bit I came up with the following solution. As I understand the logic behind ControlParameter is that when the user selects (explicitly) the observed drop down list’s index, the observing control rebinds its data using the new parameter value for the sql query. The third (second in cascade) control won’t update as the second one hasn’t self-select new index – it changed the underlying data source (thus the selected item value)! In order to fix this, I propose to override the DataBound event of the observed control so that it explicitly kicks its observers to DataBind their values.

.html:

<asp:DropDownList id="Foo" OnDataBound="Foo_DataBound" />

.cs:

protected void Foo_DataBound(object sender, EventArgs e)
{
    m_observingControl.DataBind();
}

If you have a better solution, I am glad to hear it!

Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: