Thursday 20 March 2014

gridview sorting in asp.net

ASP.NET provides a many for showing data and GridView Control is one of them. GridView control, used  for all CRUD operation display, edit and delete data from different kinds of data sources.
As Gridview is used to display huge amount of data, its make page very clumsy id displaying all data in one page and very hard to findout the particular value; due to it there is very wonderful property of sorting all the grid value.


First need to do the allowSorting=true; it activate the sorting in grid;
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"


There need to handle grid event as Sorting which will change the while click on header for sorting.
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
      OnSorting="GridView1_Sorting"> </asp:GridView>



Now handling the Sorting event in code behind c#.
    protected void SetSortDirection(string sortDirection)
    {
        if (sortDirection == "ASC")
        {
            _sortDirection = "DESC";
        }
        else
        {
            _sortDirection = "ASC";
        }
    }
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        SetSortDirection(SortDireaction);
        if (dataTable != null)
        {
            //Sort the data.
            dataTable.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
            SortDireaction = _sortDirection;
        }
    }



No comments:

Post a Comment