title: Sorting gridview column in asp.net
body: <p>I have a gridview that loads data from database. The data is displayed in the gridview for the first time sorted by datetime. On one column of that gridview I want to allow sorting, for example on the main_post column. I had tried this, but the gridview still did not sort when I click the header of the column.</p>
  
  <p>This is my front-end code for gridview:</p>
  
  <pre><code>&lt;asp:DataGrid ID="Datagrid1" runat="server" 
      AllowPaging="True" 
      AllowSorting="True" 
      OnSorting="ComponentGridView_Sorting"&gt;
      &lt;Columns&gt;
          &lt;asp:BoundColumn DataField="main_post" HeaderText="Header Post ID" 
              SortExpression="ComponentGridView_Sorting" /&gt;
      &lt;/Columns&gt;
  &lt;/asp:DataGrid&gt;
  </code></pre>
  
  <p>My back-end code:</p>
  
  <pre><code>protected void loadData()
  {
      DataTable dtTemp;
      dtTemp = objDBInterface.getResults(strSQL);
      Datagrid1.DataSource = dtTemp;
      Datagrid1.DataBind();
      ViewState["dtbl"] = dtTemp;
  }
  
  protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
      {
          DataTable dataTable = ViewState["dtbl"] as DataTable;
          if (dataTable != null)
          {
              DataView dataView = new DataView(dataTable);
              dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
              Datagrid1.DataSource = dataView;
              Datagrid1.DataBind();
          }
      }
      private string ConvertSortDirection(SortDirection sortDirection)
      {
          string newSortDirection = String.Empty;
          switch (sortDirection)
          {
              case SortDirection.Ascending:
                  newSortDirection = "ASC";
                  break;
              case SortDirection.Descending:
                  newSortDirection = "DESC";
                  break;
          }
  
          return newSortDirection;
      }
  </code></pre>
  
  <p>I dont have any error and I dont know where my mistake is, could somebody please help me to solve this problem?</p>
  
  <p>Thanks in advance.</p>