Possible Duplicate:
Populate one dropdown based on selection in another
I have 3 Dropdown list on my aspx page. First one is hard coded with 4 values. The second one should be populated programatically, for ex. if I select "Product1" in first dropdown, then second dropdown should be populated with values like "Model1_1", "Model1_2". If I select "Product2" then the second dropdown is populated with "Model2_1", "Model2_2").
Could you give me some help ?
1 Set AutoPostBack="true"
on first DropDownList1 and add OnSelectIndexChanged="YourDelegate"
.
2 In your delegate when you post data, bind your second DropDownList2 with prefix SelectedValue
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var value = DropDownList1.SelectedValue;
if(value == "Product1")
{
....
}
else if(value == "Product2")
{
....
}
}
I could name 2 solutions to this questions.
First one involves using Cascading Drop Down from the AJAX Toolkit for ASP.NET pages.
You have here references and an example:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx
It is somehow cleaner
and it doesn't cause postbacks, but you have to use that toolkit. But it is nice to learn to use it, because it offers others nice facilities.
The second involves adding for your DropDownList a handler for the OnSelectedIndexChange event. So when the user selects a value from the first dropdown, the server side catches the event and populates the second DropDown with the necessary values. Due to the fact that this requires server side operations, it can be rather annoying to reload the page after a selection is made. The client side should look like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack = true OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
Where in the server side:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList2.Items.Clear();
DropDownList2.Items.Add("text");
....
}
you can populate second drp (DropDownList) by this ways: Connect 1st drp with table, which calls this query: (in SQLDataSource1)
SELECT [id], [name] FROM Products
in 2nd drp you should call (in SQLDataSource2)
SELECT [id], [name] FROM Models WHERE ProductID=@Product_id
in SQLDataSource2
select command
Property add Parameter value for Product_id
it must be drp1.SelectedValue
Note: Don't forget Enable AutoPostBack
for drp1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With