2012-01-02 70 views
2

我有一個GridView和它的數據源來自的LINQ to SQL語句:GridView的排序在ASP.NET

var query = from user in dataContext.tbl_files 
      select new { user.File_Name, user.Upload_Time, user.Uploaded_By }; 

GridView1.DataSource = query.ToList(); 
GridView1.DataBind(); 

我想實現GridView中的排序功能:

public void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    string previousSortExpression = (string)ViewState["SortDirection"]; 
    string sortExpression = e.SortExpression; 
    SortDirection sortDirection = e.SortDirection; 
    if (sortExpression.Equals(previousSortExpression)) 
    { 
     sortDirection = SortDirection.Descending; 
     ViewState["SortDirection"] = string.Empty; 
    } 
    else 
     ViewState["SortDirection"] = sortExpression; 

    string direction = sortDirection == SortDirection.Ascending ? "ASC" : "DESC"; 
    e.SortExpression = string.Format("it.{0} {1}", e.SortExpression, direction); 

    DataTable dataTable = (DataTable)GridView1.DataSource; // here returns null! 

    if (dataTable != null) 
    { 
     DataView dataView = new DataView(dataTable); 
     dataView.Sort = e.SortExpression ; 
     GridView1.DataSource = dataView; 
     GridView1.DataBind(); 
    } 
} 

" DataTable dataTable = (DataTable)GridView1.DataSource; "行返回null,但是數據源的計數是4.我得到這個錯誤:

{「無法強制轉換'System.Colle ctions.Generic.List 1[<>f__AnonymousType0 3 [System.String,System.Nullable`1 [System.DateTime的],System.String]]」爲類型 'System.Data.DataTable'。「}

我怎樣才能排序我的GridView並糾正我的錯誤?謝謝..

+0

你爲什麼不使用LINQ2SQL數據源,thisway您整理作品開箱? – Pleun 2012-01-03 21:42:51

回答

2

您不能使用網格的DataSource屬性來獲取數據源。它只有在設置和回髮結束後纔可用。您需要再次從數據庫中獲取數據。
事情是這樣的:

public void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    var users = (from user in dataContext.tbl_files 
       select new { user.File_Name, user.Upload_Time, user.Uploaded_By }).ToList().AsEnumerable(); 

    switch(e.SortExpression) 
    { 
    case "File_Name": 
     users = users.OrderBy(x => x.File_Name); 
     break; 
    case "Upload_Time": 
     users = users.OrderBy(x => x.Upload_Time); 
     break; 
    case "Uploaded_By": 
     users = users.OrderBy(x => x.Uploaded_By); 
     break; 
    } 
    if(e.SortDirection == SortDirection.Descending) 
    users = users.Reverse(); 

    GridView1.DataSource = users; 
    GridView1.DataBind(); 
} 
1

上面的回答是正確的,首先您需要指定數據源,如排序事件被稱爲再次GridView控件。

所以必須將數據存儲在某個地方。

對於從電網獲取的數據源,你可以遵循以下步驟

問題在於,你要分配LINQ結果作爲GridView的數據源的,然後從gridview的數據源採取的數據表。

試試這個代碼

BindingSource bs = (BindingSource)Gv.DataSource; 
DataTable Dt = (DataTable) bs.DataSource; 

聯繫,如果您有任何疑問

+0

BindingSource不可識別。我們應該添加任何命名空間嗎? – user741319 2012-01-02 13:20:42