Asp.net

回發後 GridView 未正確重新綁定

  • September 12, 2017

我有一個指向 ObjectDataSource 的 DataSourceID 的 GridView。ObjectDataSource 指向一個方法,該方法使用 ObjectDataSource 控制項的 TypeName、SelectMethod 和 SelectCountMethod 屬性返回 LINQ IQueryable。發生的情況是數據預先正確載入。但是,在回發時,如果我從 GridView 中刪除行並嘗試使用顯式 GridView.DataBind() 重新綁定,則它不起作用。我知道 LINQ 正在返回正確的行數等,因為我呼叫了 countmethod 並且它返回了正確的行數。這是一個簡單的例子:

<asp:GridView ID="TestGridView" runat="server" PageSize="20" 
   AutoGenerateColumns="false" AllowPaging="true" 
   AllowSorting="false" DataSourceID="TestDataSource">
   <Columns>
       ...
   </Columns>
</asp:GridView>

<asp:ObjectDataSource ID="TestDataSource" runat="server" 
   EnablePaging="true" SelectCountMethod="GetDetailCount" 
   SelectMethod="GetDetails" TypeName="MyApp.PageClass" />

我嘗試添加一個按鈕並添加 TestGridView.DataBind(); 方法。我嘗試將它添加到 Page_PreRender 事件中。無論我嘗試什麼,它都不起作用。

正如下面有人建議的那樣,我也嘗試將其移至 Page_Load ,但不行。這是我的程式碼的粗略範例:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
       // Set "initial" query parameters, then ...
       BindData();
   }
}

private void BindData()
{
   // EDITED: Removed the code below since I'm not looking to delete the
   //         rows from the database, but rather get the GridView to rebind
   //         which its not.
   ////Remove all current rows from the GridView
   //int colCount = TestGridView.Rows.Count;
   //for (int x = 1; x <= colCount; x++)
   //{
   //    TestGridView.DeleteRow(x);
   //}

   // Bind GridView to the ObjectDataSource
   TestGridView.DataBind();
}

protected void RegenerateImageButton_Click(object sender, ImageClickEventArgs e)
{
   // Set "updated" query parameters, then ...
   BindData();
}

Gridview 不會在回發時重新綁定,它們的行會從視圖狀態中拉回。在頁面載入(或初始化?)時將 gridview 的 DatasourceID 重置為對像數據源 ID 將導致 gridview 被反彈。

愚蠢的想法,但是您是否使用 ? 檢查了頁面載入事件if(!Page.IsPostBack)

來自ASP.NET 頁面框架概述

Page_Load:在此事件期間,您可以執行一系列操作來首次創建 ASP.NET 頁面或響應文章產生的客戶端事件。在此事件之前已恢復頁面和控制項視圖狀態。使用IsPostBack頁面屬性檢查這是否是第一次處理頁面。如果是第一次,請執行數據綁定。此外,讀取和更新控制項屬性。

然而

**Page_PreRender:**在保存視圖狀態和呈現控制項之前觸發 PreRender 事件。您可以使用此事件對控制項執行任何最後一分鐘的操作。

有效

因為頁面框架是一個無狀態的a和斷開的模型,每次客戶端請求一個.aspx頁面時,頁面處理過程中都會發生很多事情……

因此,實際上,您可以在設置視圖狀態之前而不是在恢復視圖狀態之後進行檢查。最常見的檢查if(!Page.IsPostBack)位置通常是在 Page_Load 事件中。

引用自:https://stackoverflow.com/questions/1759325