2011-10-17 2 views
3

안녕 얘들 아 Allowporting = "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)은 항상 null입니다. 사전에

감사

답변

0

당신은 잘못 여러 가지가 있습니다

  1. 귀하의 방법 PopulateGridView이있는 gridview에 IQuerable을 결합, 아직 당신이 OnSorting 처리 할 때와 같은 DataTable을 얻을 수있을 척을 GridView의 DataSource.

  2. 이 줄 : DataTable dataTable = grd_sample.DataSource as DataTable;은 항상 NULL을 반환합니다. 그리드 뷰는 DataSource에 대한 참조를 유지하지 않기 때문에 항상 NULL을 반환합니다. 데이터를 다시 가져 와서 정렬하고 다시 바인딩해야합니다. 즉, 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

고마워요. 당신의 코드를 시험해 보았습니다. 그러나 나는 한 줄을 바꿔야했다. if (e.SortDirection.ToString() == "Ascending") .. 다시 한번 고마워요! – anonymous1110