Keeping Data in GridView after PostBack

ε祈祈猫儿з 提交于 2019-12-18 08:58:15

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/18160368/keeping-data-in-gridview-after-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!