C# – Gridview sorting when databinding from codebehind file

asp.netcgridviewwebforms

I am using asp.net web-form and gridview on several pages to display data. I bind gridview from codebehind file.

SO far i am able to use following code to bind datasource to gridview and also enable paging but i a facing problem to enable sorting on the same grid. Any point or help regarding how to enable paging to make it work with the below code.

I also have addition fields which are not part of this code which i use for additional functionality
onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand"

.ASPX File

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID" 
           Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5" 
            Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader"  AllowSorting="true" 
             onrowdatabound="GridView1_RowDataBound"  onrowcommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging" >
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date"  DataFormatString="{0:yyyy/MM/dd}"/>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle  Height="32px" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" BorderStyle="None" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#242121" />
            <RowStyle   BorderColor="#f5f5f5" BorderStyle="Notset"/>
   </asp:GridView>

CODE BEHIND

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        GetDetails();
    }
}   


   protected void GetDetails()
{
    string strSql = "SELECT * FROM Test_Table Order by Date Desc ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    GridView1.DataSource = ds;
    GridView1.DataBind();

}

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    GetDetails();
}

UPDATE: Code updated to

.ASPX

OnSorting="GridView1_OnSorting"

CODE BEHIND

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
    string strSql = "SELECT * FROM Test_Table ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    DataTable dataTable = ds.Tables[0];
    DataTable dataTable = ds.Tables[0];

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " "+e.SortDirection;
        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}

Best Answer

You should create sorting event like this :

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
    {

        //TODO write tour code here to get data from database;
         DataTable dataTable = your datatable get from your db;

        if (dataTable != null)
        {
                if (e.SortDirection.ToString() == "Ascending")
                {
                    dataView.Sort = e.SortExpression + " ASC";
                }
                else if (e.SortDirection.ToString() == "Descending")
                {
                    dataView.Sort = e.SortExpression + " DESC";
                }

            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " "+e.SortDirection;
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }


**e.SortExpression** provides sorting column name 

**e.SortDirection** provides sorting direction like ASC or DESC.

Also you can take sort direction in view state on page

private string GridViewSortDirection
    {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

private void SetSortDirection()
        {
            GridViewSortDirection = (GridViewSortDirection.ToUpper() == "DESC") ? "ASC" : "DESC";
        }

I hope above code help you.

Related Topic