1. Original Entry + Comments2. Write a Comment3. Preview Comment
New comments for this entry are disabled.


October 13, 2006  |  Cascading drop-down lists  |  10937 hit(s)

This came up at work today, so I thought I'd toss in a quick note. You can do cascading drop-down lists declaratively in ASP.NET 2.0, or at least if your scenario is straightforward. Imagine two drop-down lists on a page:



The values available in the second one depend on the selection in the first one.

Update I've also added a post about cascading drop-down list in the EditItemTemplate of a FormView control.


You can do this with two DropDownList controls, of course, and two datasource controls, each of which does a query. The first one gets all the records for the first drop-down list. The second datasource control has a parameterized query that looks like this:
SELECT Model FROM Models WHERE (Manufacturer = @Manufacturer)
(If you, like, I, are using an Access mdb file for your test, the variable is a question mark.)

The trick to this, such as it is, is in how you get the parameter value. Since the second list depends on the selection in the first list, you can create a ControlParameter to get the first list's selection. The markup for the complete second datasource control might look like this:
<asp:AccessDataSource ID="AccessDataSource2" 
runat="server"
DataFile="~/App_Data/Cars.mdb"
SelectCommand="SELECT Model, ModelID FROM Models WHERE (Manufacturer = ?) ORDER BY Model">
<SelectParameters>
<asp:ControlParameter
ControlID="DropDownList1"
Name="Manufacturer"
PropertyName="SelectedValue"
Type="String" />
</SelectParameters>
</asp:AccessDataSource>
Make sense? The query for this datasource control reads the selected value from the first drop-down list and then passes it as a parameter to the query.

This works (for me) even if the selection in the first list ends up returning no hits for the second list.

I've posted the complete page separately here.




Kabelo   01 Apr 08 - 7:16 AM

I keep getting an error message saying I should declare "LabelSelection"

<script runat="server">
Protected Sub DropDownlost5_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
LabelSelection.Text = DropDownList4.SelectedItem.Text & " " & DropDownList5.SelectedItem.Text
End Sub
</script>


 
mike   01 Apr 08 - 7:20 AM

Somewhere in the page you need this:
<asp:Label ID="labelSelection" runat="server" />



 
Kabelo   01 Apr 08 - 11:38 PM

I got it,

Thanx