Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c# - Keeping Data in GridView after PostBack

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...