2013-10-14 159 views
1

當我在GridView.ROWDATABOUND事件中動態創建按鈕時,出現asp.net 4.5中的錯誤。對於按鈕ASP Gridview無法加載視圖狀態。

代碼:

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.

需要一個解決方案..!

+0

嘗試將此按鈕放入標記中。 – Fals

+0

這會破壞結構。這在以前的版本中工作,其中既沒有ajax也沒有更新面板。現在它變成垃圾,我不知道爲什麼或做什麼 – gayan1991

+0

你剛纔說的anwnsear。 Unfortanally Update Panel有很多問題,其中一個問題是View State管理。每個控件都必須在Page_OnInit中創建,才能讓您獲得一些成功! – Fals

回答

2

如果您嘗試在控件集合中的某處添加控件,那麼您肯定會遇到視圖狀態問題。由於每個動態控件的MSDN specification在Asp.net

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

所以可能的解決方案,這可能在你的頁面中使用Placeholder,您可以添加動態控制。這將在Control集合中保留索引,並且還會處理View狀態。由於新添加的控件將從佔位符控件中查看狀態。

相關問題