2011-05-09 34 views
1

我運行此事件處理程序和方法進行梳理我的GridView控件,但最高審計機關,它是空:排序後GridView變爲NULL?

protected void OtherGridView_Sorting(object sender, GridViewSortEventArgs e) 
    { 
     DataTable dtSortTable = gvMeldingen.DataSource as DataTable; 

      DataView dvSortedView = new DataView(dtSortTable); 
      dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection); 
      gvMeldingen.DataSource = dvSortedView; 
      gvMeldingen.DataBind(); 

    } 
    private string getSortDirectionString(SortDirection sortDirection) 
    { 
     string newSortDirection = String.Empty; 
     if (sortDirection == SortDirection.Ascending) 
     { 
      newSortDirection = "ASC"; 
     } 
     else 
     { 
      newSortDirection = "DESC"; 
     } 
     return newSortDirection; 
    } 

請幫助我。先謝謝你!

這是我得到的錯誤:在使用DataView之前必須設置DataTable。

這凸顯:dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection)

+0

是dtSortaTable空每次設置DataSource?您能否在頁面的Load事件中發佈代碼? – Larry 2011-05-09 07:25:57

+0

有沒有加載事件 – SamekaTV 2011-05-09 07:27:08

+0

我得到這個錯誤:DataTable必須在使用DataView之前設置。 並突出顯示:dvSortedView.Sort = e.SortExpression +「」+ getSortDirectionString(e.SortDirection); – SamekaTV 2011-05-09 07:28:35

回答

2

DataSource屬性在往返過程中丟失。這就是爲什麼DataTable dtSortTable = gvMeldingen.DataSource as DataTable;爲空,且DataView dvSortedView = new DataView(dtSortTable);無效。

當您在數據網格上點擊排序超鏈接時,會觸發從客戶端到服務器的回發。然後,ASP.NET使用持久數據(如ViewState等)構建回覆頁面。

The DataSource屬性不是持續狀態往返之間的一部分,這就是爲什麼它的價值丟失。

一個解決辦法是重新查詢你的數據源如下:

protected void OtherGridView_Sorting(object sender, GridViewSortEventArgs e) 
    { 
     var SortExpression = e.SortExpression + " " + getSortDirectionString(e.SortDirection); 

     gvMeldingen.DataSource = ... // Requery the Data using the new sort expression above 
     gvMeldingen.DataBind(); 
    } 

另一種方案是在Page_Load事件(不推薦)

+0

這給出了錯誤,看看你在哪裏直接指定類型SortExpression。 – SamekaTV 2011-05-09 07:45:15

+0

以及gvMeldingen的數據源呢? – SamekaTV 2011-05-09 07:45:49

+0

關於gvMeldingen的DataSource,你能否在第一次填寫它的代碼片段? – Larry 2011-05-09 08:01:14

0

當你把一個DataViewDataTable左右,該方法將只工作在第一時間(假設數據源是從開始DataTable)。下一次數據源是DataView,並且您不能將其投射到DataTable

使用DataTable的默認視圖作爲開始時的數據源,以便數據源始終爲DataView。然後,您可以從源代碼獲取視圖,並從中獲取底層表格:

DataView view = gvMeldingen.DataSource as DataView; 
DataTable dtSortTable = view.Table; 
+0

我不確定數據源是否在往返之間持續 – Larry 2011-05-09 07:31:20

+0

這是我在代碼之後得到的錯誤:對象引用未設置爲對象的實例。 – SamekaTV 2011-05-09 07:32:04

+0

這部分突出顯示:DataTable dtSortTable = view.Table; – SamekaTV 2011-05-09 07:32:34