Click here to Skip to main content
15,917,628 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hallo,

I want to change the datasource of a listbox dynamically, i.e. modify the select statement in the SQLDatasource, depending on which button is clicked. How can I do that? This is how my Listbox looks like:

XML
<asp:ListBox ID="lst_objects" runat="server" DataSourceID="SqlDataSource1"
                    DataTextField="field1" DataValueField="field2"></asp:ListBox>
Posted

Hi,

you can change your sqldatasource on button click event


C#
SqlDataSource1.SelectCommand = "";
     ListBox.Datasource = SqlDataSource1;
     ListBox.DataTextField = "displayfieldid";
     ListBox.DataValueField = "valuefieldid";
     ListBox.DataBind();


By using this code you can change your select command query also

All the Best
 
Share this answer
 
C#
lst_objects.DataSourceID=sqlDataSource1;
lst_objectsDataTextField="field1";
lst_objects.DataValueField="field2";
lst_objects.DataBind()  //Very Important
 
Share this answer
 
In your example you have given datasourceID, dataTextfield in htmlSource but it's static.
do the same thing in code behind to make it dynamic, here is code. call it on button click.

C#
lstBox.DataSourceID=sqlDataSource1;
lstBox.DataTextField="fld1";
lstBox.DataValueField="fld2";
lstBox.DataBind();
 
Share this answer
 
Comments
chris085 13-Oct-11 5:18am    
So you mean to remove the code in the aspx file and to add this to the code behind? or what should be kept in the aspx?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900