2011-02-08 60 views
2

我在我的GridView使用RowDataBound事件進行條件格式更改數據:Asp.net GridView - 爲什麼DataRowBound在排序上發生改變?

void gvReg_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 

     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 

      DateTime lastUpdate DateTime.Parse(DataBinder.Eval (e.Row.DataItem, "LAST_UPDATE"); 

      if (lastUpdate < DateTime.Today.AddMonths(-1)) 
      { 

      Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate"; 
      hypLastUpdate.CssClass = "Error"; 
      hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com"; 

      } 

     } 

    } 

這工作,並設置適當的CssClass到超鏈接(這使得它大膽的紅色的一個不和諧的陰影),但一旦gridview被排序(通過用戶點擊一個列標題),css類會在hypLastUpdate上重置,並丟失它的樣式和關聯的NavigateUrl屬性。

控件hypLastUpdate包含在GridView的模板字段中,它的文本值是綁定到名爲「LAST_UPDATE」的字段的數據。

這是一個計劃的行爲(排序應該打破在RowDataBound事件中完成的條件格式?)還是有我可以檢查以確保我沒有做不正確的事情?

我沒有在後面的代碼中的任何地方使用DataBind方法,並且viewstate已針對有問題的gridview打開。

- 編輯 -

它結束了在事件處理是錯誤的。

我做:

gvReg.Sorted += {SomeEventHandler} 

裏面的頁面加載事件,但只有當它不是一個回發。這個函數在網格視圖排序後調用gvReg.DataBind。我刪除了處理程序連線,而是將事件處理函數添加到OnSorted事件中。我猜分配給GridView的委託沒有保存在ViewState之間的回調?

+1

對網格視圖排序事件你需要重新綁定數據`gvReg.DataBind();`。所以,這意味着你需要重新綁定你的數據源與數據排序(通過排序數據集或重新查詢您的數據庫基於`pSortExpression = e.SortExpression;`和`pSortDirection =(pSortDirection == SortDirection.Ascending?SortDirection.Descending:SortDirection .Ascending);``保護無效gvReg_Sorting(對象發件人,GridViewSortEventArgs e)'事件,以便`gvReg_RowDataBound`將被再次調用。在執行此操作之前,您可能需要檢查'e.SortExpression.Length> 0` – 2011-02-08 22:45:06

+1

@wllmsaccnt :在你的RowDataBound事件處理程序中設置一個斷點,這個事件處理程序在排序後到達了嗎? – 2011-02-08 23:07:44

回答

4

嗨,這裏是我的評論意思的一個簡單例子。這是我能想到的唯一方法:

protected void gvReg_Sorting(object sender, GridViewSortEventArgs e) 
    { 
     GridView gridView = (GridView)sender; 

     if (e.SortExpression.Length > 0) 
     { 
      foreach (DataControlField field in gridView.Columns) 
      { 
       if (field.SortExpression == e.SortExpression) 
       { 
        cellIndex = gridView.Columns.IndexOf(field); 
        break; 
       } 
      } 

      if (pSortExpression != e.SortExpression) 
      { 
       pSortDirection = SortDirection.Ascending; 
      } 
      else 
      { 
       pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending); 
      } 
      pSortExpression = e.SortExpression; 
     } 

     //Retrieve the table from the database 
     pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC"; 
     List<Partners> partnerList = GetPartnerList(); 

     gvReg.DataSource = partnerList; 
     gvReg.DataBind(); 

    }