Asp.net
GridView 不記得回發之間的狀態
我有一個帶有數據綁定網格(綁定到對像源)的簡單 ASP 頁面。網格位於嚮導的頁面內,每行都有一個“選擇”複選框。
在嚮導的一個階段,我綁定了 GridView:
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e) { ... // Bind and display matches GridViewMatches.EnableViewState = true; GridViewMatches.DataSource = getEmailRecipients(); GridViewMatches.DataBind();當點擊完成按鈕時,我遍歷行並檢查選擇的內容:
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { // Set the selected values, depending on the checkboxes on the grid. foreach (GridViewRow gr in GridViewMatches.Rows) { Int32 personID = Convert.ToInt32(gr.Cells[0].Text); CheckBox selected = (CheckBox) gr.Cells[1].FindControl("CheckBoxSelectedToSend");但是在這個階段GridViewMatches.Rows.Count = 0!我不重新綁定網格,我不應該需要,對吧?我希望視圖狀態保持狀態。(另外,如果我重新綁定網格,我的選擇複選框將被清除)
注意:此頁面還在 OnInit 方法中動態添加使用者控制項。我聽說它可能會弄亂視圖狀態,但據我所知,我做得正確,並且那些添加的控制項的視圖狀態似乎有效(值在回發之間保持不變)
非常感謝您的幫助!
瑞安
更新:這可能與我以程式方式設置數據源的事實有關嗎?我想知道 asp 引擎是否在頁面生命週期中將網格數據綁定到尚未定義的數據源。(在測試頁面中,GridView 是“自動”數據綁定的。我不希望網格重新綁定我只想要上一篇文章中視圖狀態的值!
另外,我在 asp 標頭中有這個:ViewStateEncryptionMode=“Never” - 這是為了解決偶爾出現的“無效的 Viewstate Validation MAC”消息
作為參考,我的 GridView 定義如下:
<asp:GridView ID="GridViewMatches" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnDataBinding="GridViewMatches_OnBinding"> <Columns> <asp:BoundField DataField="PersonID"><ItemStyle CssClass="hidden"/></asp:BoundField> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="CheckBoxSelectedToSend" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "SelectedToSend") %>'/> </ItemTemplate> ...
迭代 PreInit 事件中的控制項(以檢測是否按下了“添加另一個控制項”或“刪除另一個控制項”按鈕)會使視圖狀態無效!
這是從 PreInit 呼叫的方法
public Control GetPostBackControl(Page thePage) { //return null; Control myControl = null; string ctrlName = thePage.Request.Params.Get("__EVENTTARGET"); if (((ctrlName != null) & (ctrlName != string.Empty))) { myControl = thePage.Master.FindControl(ctrlName); } else { foreach (string Item in thePage.Request.Form) { Control c = thePage.Master.FindControl(Item); if (((c) is System.Web.UI.WebControls.Button)) { myControl = c; } } } return myControl; }(我不相信這種方法,我是在網上找到的)
如果第一行未註釋,則保持視圖狀態。
可怕!