回发后将数据保留在 GridView 中 [英] Keeping Data in GridView after PostBack
问题描述
我有一个与 SqlDataSource
关联的 GridView
.
I have a GridView
which is associated with an SqlDataSource
.
当我单击 Button
时,我更改了 SelectCommand
,然后使用 DataBind
更新 GridView
.
When I click a Button
, I change the SelectCommand
and then I use DataBind
to update the GridView
.
PostBack 后,我希望保留最新的数据,我不希望 GridView
被原始 SelectCommand
加载.
After PostBack, I want the latest Data to Remain, I don't want the GridView
to be loaded by the original SelectCommand
.
我知道这是由一种叫做 ViewState
的东西完成的,但我没有设法以正确的方式实现它.
I know this is done by something called ViewState
, but I didn't manage to implement it in the right way.
我在网格本身上尝试了 EnableViewState="true"
和 EnableViewState="false"
,但没有成功.
I tried both EnableViewState="true"
and EnableViewState="false"
on the Grid itself, with no luck.
代码
<asp:GridView ID="GridView1" ...... DataSourceID="UsersSource" >
<asp:SqlDataSource ID="UsersSource" ... SelectCommand="SELECT * FROM USERS"></asp:SqlDataSource>
在启动时,GridView
填充了 SELECT * FROM USERS
的结果.
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();
GridView
填充了新数据.
现在让我们说,我点击一个表头对这个表进行排序,会有一个回发,在它之后,这个表中的数据将包含第一个查询的结果.
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.
这里需要做什么?
更多信息
声明:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin" %>
页面加载方法中没有任何内容.
There's nothing in the Page Load method.
推荐答案
这是设计使然.这里的问题是 SqlDataSource 在页面加载时被重新创建,它不会在回发时维护 selectcommand,而是恢复到创建 DataSource 时设置的那个.
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.
所以你需要告诉 SqlDataSource 它上次正确加载时 SelectCommand
的内容.
So you need to tell the the SqlDataSource what it had for SelectCommand
when it last loaded correctly.
只需将 SQL COMMAND 存储在 ViewState 中,并通过在 Page 指令上设置 ViewStateEncryptionMode
来启用加密以保护内容.[始终以安全为标准]
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"];
这篇关于回发后将数据保留在 GridView 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!