Monday, 16 March 2009

Implement datetime (and other) sorting in ASP.NET gridview

We need some code to load data into the table, then we use the following functions (also add the gridView_Sorting function to handle the OnSorting event of the grid, in the gridview definition in the .aspx file (OnSorting="gridView_Sorting"), same for OnPageIndexChanging event: OnPageIndexChanging="gridView_PageIndexChanging").


   1:  static SortDirection lastSortDirection = SortDirection.Ascending;
   2:  static DataTable roadmapTable;
   3:   
   4:  static string ConvertSortDirectionToSql(SortDirection sortDirection)
   5:  {
   6:      string m_SortDirection = String.Empty;
   7:   
   8:      switch (sortDirection)
   9:      {
  10:      case SortDirection.Ascending:
  11:          m_SortDirection = "ASC";
  12:          break;
  13:   
  14:      case SortDirection.Descending:
  15:          m_SortDirection = "DESC";
  16:          break;
  17:      }
  18:   
  19:      return m_SortDirection;
  20:  }
  21:   
  22:  protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
  23:  {
  24:      roadmapGridView.PageIndex = e.NewPageIndex;
  25:      roadmapGridView.DataBind();
  26:  }
  27:   
  28:  protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
  29:  {
  30:      if (roadmapTable == null)
  31:      {
  32:          return;
  33:      }
  34:   
  35:      lastSortDirection = lastSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
  36:   
  37:      DataView m_DataView = new DataView(roadmapTable);
  38:      m_DataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(lastSortDirection);
  39:      roadmapGridView.DataSource = m_DataView;
  40:      roadmapGridView.DataBind();
  41:  }

No comments: