2011-10-17 42 views
3

嗨,大家好,我想通過設置AllowSorting =「True」來排序我的asp網格。我也爲活動添加了代碼,但是我似乎無法使其工作。排序在GridView asp網格

private void PopulateGridView() 
    { 
     var a = from c in sample_worker.get() 
       select new 
       { 
        c.CemID, 
        c.Title, 
        c.Description 
       }; 
     grd_sample.DataSource = a; 
     grd_sample.DataBind(); 


    } 

這是填充網格的代碼。我加入這個!下面的IsPostBack ..

排序的代碼..

 private string ConvertSortDirectionToSql(SortDirection sortDirection) 
    { 
     string newSortDirection = String.Empty; 

     switch (sortDirection) 
     { 
      case SortDirection.Ascending: 
       newSortDirection = "ASC"; 
       break; 

      case SortDirection.Descending: 
       newSortDirection = "DESC"; 
       break; 
     } 

     return newSortDirection; 
    } 
    protected void grd_sample_Sorting(object sender, GridViewSortEventArgs e) 
    { 

     DataTable dataTable = grd_sample.DataSource as DataTable; 


     if (dataTable != null) 
     { 
      DataView dataView = new DataView(dataTable); 
      dataView.Sort = e.SortExpression + " " +   ConvertSortDirectionToSql(e.SortDirection); 

      grd_sample.DataSource = dataView; 
      grd_sample.DataBind(); 
     } 

    } 

我能做些什麼來解決這個問題..還我能夠把它整理來回? desc - asc - desc。 if(dataTable!= null)也總是爲空。

在此先感謝

回答

0

你有很多事情錯:

  1. 你的方法PopulateGridView結合的IQuerable到你的GridView,但是當你處理OnSorting你假裝能得到一個DataTable作爲你的GridView的數據源。

  2. 此行:DataTable dataTable = grd_sample.DataSource as DataTable;將始終返回NULL,因爲您的gridview不保留對DataSource的引用。您需要重新提取數據,對其進行分類並重新綁定。換句話說,你需要做這樣的事情上grd_sample_Sorting

    protected void grd_sample_Sorting(object sender, GridViewSortEventArgs e) 
    { 
    var a = from c in sample_worker.get() 
          select new 
          { 
           c.CemID, 
           c.Title, 
           c.Description 
          }; 
    
        if(e.SortDirection=="ASC") 
        { 
         if(e.SortExpression=="CemID") 
          a=a.OrderBy(x=>x.CemID); 
         else if (e.SortExpression=="Title") 
          a=a.OrderBy(x=>x.Title); 
         //And so on... 
        } 
        else 
        { 
         if(e.SortExpression=="CemID") 
          a=a.OrderByDescending(x=>x.CemID); 
         else if(e.SortExpression=="Title") 
          a=a.OrderByDescending(x=>x.Title); 
         //And so on... 
        } 
    
        grd_sample.DataSource = a; 
        grd_sample.DataBind(); 
    } 
    

但坦率地說,你可能會更好過定義您的datagridview一個的LinqDataSource。 LinqDataSource幾乎不用編寫一行代碼就可以執行分頁,排序和CRUD操作。當然不是爲了排序和分頁。

+0

謝謝你,我試過你的代碼,它工作。但是我不得不改變一條線。如果(e.SortDirection.ToString()==「升序」)..然後再次,謝謝! – anonymous1110