Context: I'm designing a simple ASP.NET webpage where I have a search box where the user can enter a User ID (int) and when they click a search button, a GridView control displays the results of a SQL SELECT query that checks if an entry with the specified User ID exists. This functionality all works and I believe is fairly simple.
I've added another button that I would like to execute a different SQL SELECT query that returns all entries in the table.
Here is the first SELECT query, which is the SelectCommand of the SqlDataSource that the GridView uses: SELECT * FROM [tblUser] WHERE [UserID] = @UserID
Here is the new SELECT query that I want to execute when a user clicks the new button: SELECT * FROM tblUser
Question: How can I use the "OnClick" event (in the code behind) to execute this new query and display the results in the same GridView?
What I've Tried: This seems like a pretty logical way of executing the new statement: change the SelectCommand of the SqlDataSource that the GridView control uses, execute that SelectCommand, then display the results of that command in the GridView. Unfortunately it just results in an empty GridView, no column labels or anything.
string selectAll = "SELECT * FROM tblUser"; //new query to execute
string oldSelect = SqlDataSource1.SelectCommand; //stores old query in temp variable
SqlDataSource1.SelectCommand = selectAll; //sets the SelectCommand of the DataSource to the new query
SqlDataSource1.Select(DataSourceSelectArguments.Empty); //executes the SelectCommand
GridView1.DataBind(); //binds the GridView to the DataSource
SqlDataSource1.SelectCommand = oldSelect; //returns the select command to its original value