Wednesday, August 18, 2010

How to bind a list of items in a dropdownlist based on the selection from another dropdownlist in asp.net?

I have Dropdownlist1 which is bound to a database. Now based on the selected item in this dropdownlist, a list of items from the database should be displayed in Dropdownlist2.How to bind a list of items in a dropdownlist based on the selection from another dropdownlist in asp.net?
I assume you are binding that list to a SqlDataSource or something like that?





If this is the case what you can do is select ';Custom Query'; when creating your datasource, and within the control, you can then do something such as





';SELECT field1 from table2 where field2=@MYVAR';





What this does is allow you to then specify @MYVAR as a parameter, you are then prompted to choose what MYVAR is, select ';Control'; and the select DropDownList1's selected value.





You can then bind that to DropDownList2, once you have done that you can trigger a DataSource2.Databind() to refresh the data





EDIT : In case you didnt use the control, i thought I would update with the manual code:





Dim myConnection As OleDbConnection


Dim myCommand As OleDbCommand


Dim myReader As OleDbDatareader


Dim strSQL As String





myConnection = New OleDbConnection(';yourconnectionstring';)





strSQL=';SELECT field1,field2 from table2 where field2=''; %26amp; datalist1.selectedvalue.tostring %26amp; ';'';





myCommand = New OleDbCommand(strSQL, myConnection)





myConnection.Open()


myReader = myCommand.ExecuteReader()


While myReader.Read()


datalist2.Items.Add(new ListItem(myReader.GetString(1).ToString, myReader.GetString(0).ToString))


End While


myreader.close()


myConnection.Close()





Obviously those apostrophes ';''; and .GetStrings may vary depending on your record types :)How to bind a list of items in a dropdownlist based on the selection from another dropdownlist in asp.net?
In DropDownList1:


- Set the DataTextField and DataValueField properties of


- Set the AutoPostBack property of DropDownList1 to true.





- Handle the OnSelectedIndexChanged in your code behind to read the SelectedValue of the Item selected of DropDownList1 and use this SelectedValue to retrieve the DataSource of DropDownList2.





Hope this helps.

No comments:

Post a Comment