回发后在GridView的数据保持 [英] Keeping Data in GridView after PostBack
问题描述
我有一个这是与相关的GridView
的的SqlDataSource
。
当我点击按钮
,我改变了的SelectCommand
然后我用的DataBind
更新 GridView控件
。
When I click a Button
, I change the SelectCommand
and then I use DataBind
to update the GridView
.
回发后,我想要最新的数据保存,我不希望 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 =真正的
和的EnableViewState =false的
在网格本身不带运气。
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>
在启动时, GridView控件
充满的结果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.
什么需要在这里完成?
更多资讯
声明:
&LT;%@页面语言=C#AutoEventWireup =真codeFILE =Admin.aspx.cs继承=管理%GT;
有什么在页面加载方法。
There's nothing in the Page Load method.
推荐答案
这是由设计。这里的问题是,在SqlDataSource被重新创建页面加载时它不保持在回发SelectCommand中,而是恢复到创建数据源时所设置的不同。
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.
只是存储在ViewState中的SQL命令,并启用加密设置 ViewStateEncryptionMode
Page指令来保护内容。 [总是选择安全性作为标准]
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"];
请参阅这篇文章由微软:<一href=\"http://connect.microsoft.com/VisualStudio/feedback/details/105069/sqldatasource-selectcommand-not-persisting-on-postback\" rel=\"nofollow\">http://connect.microsoft.com/VisualStudio/feedback/details/105069/sqldatasource-selectcommand-not-persisting-on-postback
这篇关于回发后在GridView的数据保持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!