Sorting gridview column in asp.net

Ifwat Ibrahim picture Ifwat Ibrahim · Jun 25, 2014 · Viewed 59.6k times · Source

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.

This is my front-end code for gridview:

<asp:DataGrid ID="Datagrid1" runat="server" 
    AllowPaging="True" 
    AllowSorting="True" 
    OnSorting="ComponentGridView_Sorting">
    <Columns>
        <asp:BoundColumn DataField="main_post" HeaderText="Header Post ID" 
            SortExpression="ComponentGridView_Sorting" />
    </Columns>
</asp:DataGrid>

My back-end 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;
    }

I dont have any error and I dont know where my mistake is, could somebody please help me to solve this problem?

Thanks in advance.

Answer

Shekhar Patel picture Shekhar Patel · Sep 23, 2016

Simple, set Allowsorting property true and add sorting event in your gridview.

<asp:GridView ID="GridView1" runat="server" AllowSorting="true" 
      OnSorting="GridView1_Sorting">
</asp:GridView>   

Now add Event OnSorting in .cs file

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{ 
    SetSortDirection(SortDireaction);
    if (dataTable != null)
    {
       dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection;
        GridView1.DataSource = dataTable;
        GridView1.DataBind();
        SortDireaction = _sortDirection;
    }
} 
protected void SetSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
    {
        _sortDirection = "DESC";
    }
    else
    {
        _sortDirection = "ASC";
    }
}