ASP 网格视图 无法加载视图状态

本文关键字:加载 视图状态 网格 视图 ASP | 更新日期: 2023-09-27 18:35:27

当我在事件中动态创建按钮时,我在 asp.net 4.5 中遇到错误GridView.ROWDATABOUND

按钮代码:

Dim btn1 As New Button()
btn1.ID = "btn1"
btn1.Width = "50"
btn1.Text = "Edit"
btn1.CssClass = "AdminPageBtn"
btn1.CommandName = "Edit"
btn1.CommandArgument = "Edit"
btn1.Enabled = True

e.Row.Cells(e.Row.Cells.Count - 1).Controls.Add(btn1)

我也在使用 AJAX 4.0,带有脚本管理器和更新面板。

该按钮执行以下方法

Protected Sub gvwRoutes_RowEditing(ByVal sender As Object, 
                      ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
                Handles gvwRoutes.RowEditing
End Sub

执行时,出现错误:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

需要一个解决方案..!

ASP 网格视图 无法加载视图状态

如果您尝试在控件集合中的某个位置添加控件,那么您肯定会遇到视图状态问题。根据 MSDN 规范的动态控件在 Asp.net

Inserting a dynamic control somewhere other than the end of the Controls collection 
can cause a corrupted view state

因此,可能的解决方案可能是使用页面中的Placeholder,您可以在其中添加动态控件。这将在 Control 集合的中间保留索引,并将处理视图状态。由于新添加的控件将具有占位符控件中的视图状态。