Keeping Data in GridView after PostBack

asp.net, c#, gridview, postback, viewstate

Solution

This is by design. The problem here is that the SqlDataSource gets re-created when the page loads it does NOT maintains the selectcommand on postback but rather reverts to the one that was set when the DataSource was created.

So you need to tell the the SqlDataSource what it had for `SelectCommand` when it last loaded correctly.

Just store the SQL COMMAND in ViewState and enable encryption to protect the contents by setting `ViewStateEncryptionMode` on the Page directive. [ Always choose security as a standard ]

<%@ Page ViewStateEncyptionMode="Always" %>

In your button click event store your new command in view state:

ViewState["currentCommand"] = "SELECT * FROM USERS WHERE user_id = 1";
UsersSource.SelectCommand = ViewState["currentCommand"];
GridView1.DataBind();

Now in your page load event, set it:

if( ViewState["currentCommand"] !=null)
    UsersSource.SelectCommand = ViewState["currentCommand"];

Refer to this post by Microsoft: http://connect.microsoft.com/VisualStudio/feedback/details/105069/sqldatasource-selectcommand-not-persisting-on-postback

Problem

I have a `GridView` which is associated with an `SqlDataSource`. When I click a `Button`, I change the `SelectCommand` and then I use `DataBind` to update the `GridView`. After PostBack, I want the latest Data to Remain, I don't want the `GridView` to be loaded by the original `SelectCommand`. I know this is done by something called `ViewState`, but I didn't manage to implement it in the right way. I tried both `EnableViewState="true"` and `EnableViewState="false"` on the Grid itself, with no luck. Code `<asp:GridView ID="GridView1" ...... DataSourceID="UsersSource" >` ``` <asp:SqlDataSource ID="UsersSource" ... SelectCommand="SELECT * FROM USERS"></asp:SqlDataSource> ``` On Startup, the `GridView` is filled with the results of `SELECT * FROM USERS`. Now I click a `Button`, that does the following: ``` UsersSource.SelectCommand = "SELECT * FROM USERS WHERE user_id = 1"; GridView1.DataBind(); ``` The `GridView` is filled with the new Data. Now let's say, I click on a header to sort this table, there will be a postback, and after it, the data in this table will contain the results of the first query. What needs to be done here? More Info Declaration: `<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin" %>` There's nothing in the Page Load method.

Original source