asp.net – GridView不记得回发之间的状态

前端之家收集整理的这篇文章主要介绍了asp.net – GridView不记得回发之间的状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的ASP页面与数据绑定网格(绑定到对象源).网格位于向导的页面内,每行都有一个“选择”复选框.

在向导的一个阶段,我绑定GridView:

  1. protected void Wizard1_NextButtonClick(object sender,WizardNavigationEventArgs e)
  2. {
  3. ...
  4. // Bind and display matches
  5. GridViewMatches.EnableViewState = true;
  6. GridViewMatches.DataSource = getEmailRecipients();
  7. GridViewMatches.DataBind();

单击完成按钮后,我会遍历行并检查所选内容

  1. protected void Wizard1_FinishButtonClick(object sender,WizardNavigationEventArgs e)
  2. {
  3. // Set the selected values,depending on the checkBoxes on the grid.
  4. foreach (GridViewRow gr in GridViewMatches.Rows)
  5. {
  6. Int32 personID = Convert.ToInt32(gr.Cells[0].Text);
  7. CheckBox selected = (CheckBox) gr.Cells[1].FindControl("CheckBoxSelectedToSend");

但是在这个阶段GridViewMatches.Rows.Count = 0!我不重新绑定网格,我不应该,对吧?我希望视图状态能够维持状态. (另外,如果我重新绑定网格,我的选择复选框将被清除)

注意:此页面还在OnInit方法中动态添加用户控件.我听说它可能会混淆视图状态,但据我所知,我正确地做了,并且那些添加控件的视图状态似乎有效(值在回发之间保持不变)

非常感谢您的任何帮助!

瑞安

更新:这可能与我以编程方式设置数据源的事实有关吗?我想知道asp引擎是否在页面生命周期中将网格数据绑定到尚未定义的数据源. (在测试页面中,GridView是’自动’数据绑定’.我不希望网格重新绑定我只想要来自上一篇文章的viewstate中的值!

另外,我在asp标题中有这个:ViewStateEncryptionMode =“Never” – 这是为了解决偶尔出现的“无效的Viewstate验证MAC”消息

作为参考,我的GridView定义如下:

  1. <asp:GridView ID="GridViewMatches" runat="server" AllowSorting="True" AutoGenerateColumns="False"
  2. BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3"
  3. OnDataBinding="GridViewMatches_OnBinding">
  4. <Columns>
  5. <asp:BoundField DataField="PersonID"><ItemStyle CssClass="hidden"/></asp:BoundField>
  6. <asp:TemplateField>
  7. <ItemTemplate>
  8. <asp:CheckBox ID="CheckBoxSelectedToSend" runat="server"
  9. Checked='<%# DataBinder.Eval(Container.DataItem,"SelectedToSend") %>'/>
  10. </ItemTemplate>
  11. ...

解决方法

迭代PreInit事件中的控件(以检测是否按下了“添加另一个控件”或“删除另一个控件”按钮)使视图状态无效!

这是从PreInit调用方法

  1. public Control GetPostBackControl(Page thePage)
  2. {
  3. //return null;
  4.  
  5. Control myControl = null;
  6. string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
  7. if (((ctrlName != null) & (ctrlName != string.Empty)))
  8. {
  9. myControl = thePage.Master.FindControl(ctrlName);
  10. }
  11. else
  12. {
  13. foreach (string Item in thePage.Request.Form)
  14. {
  15. Control c = thePage.Master.FindControl(Item);
  16. if (((c) is System.Web.UI.WebControls.Button))
  17. {
  18. myControl = c;
  19. }
  20. }
  21.  
  22. }
  23.  
  24. return myControl;
  25. }

(我不相信这个方法,我在网上找到它)

如果取消注释第一行,则维护视图状态.

可怕!

猜你在找的asp.Net相关文章