Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate Dropdown list based on another dropdown list [duplicate]

Tags:

c#

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 ?

like image 638
N K Avatar asked Sep 04 '12 07:09

N K


3 Answers

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")
   { 
    ....      
   }
 }
like image 120
Aghilas Yakoub Avatar answered Oct 19 '22 13:10

Aghilas Yakoub


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");
    ....
}
like image 38
Coral Doe Avatar answered Oct 19 '22 13:10

Coral Doe


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

like image 2
Emin Hasanov Avatar answered Oct 19 '22 11:10

Emin Hasanov