Keeping Data in GridView after PostBack

蹲街弑〆低调 提交于 2019-11-29 15:27:13

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

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