Sorting Gridview control on header click with pagination Asp.net C#

 Overview: Asp.net sorting Gridview control  on column header click in Ascending or Descending order,  binding with DataTable Asp.net c# with pagination. In this article, I am going to give some overview on how to  SORT the data when user click on Gridview Header cell  (i.e) Sorting Gridview control in Asp.net.

Also, I recommend you have a look at my Previous Article about Gridview Add/Update/Delete functionality ( CRUD ) or Gridview row color change based on data.

Though there are a lot of articles on web which explains paging and sorting, there’s some reasons which differ this article from other articles. ie Here Gridview control is bind with Datatable as in another article you found using `ObjectDataSource` also Paging not supported.

Recently I was working with GridView control and I was having manipulated Datatable as a DataSource to it. While solving this, I developed a good piece of code which I do feel will help most of you in your development activity.


HTML Markup :

  1. Set `AllowPaging=”True”` and `AllowSorting=”True”` Properties of GridView to enable paging and sorting respectively.
  2. Set PageSize property to mention how many records will be displayed on each page.
  3. Set `SortExpression` property of each column.
//*
<asp:GridView ID=”gvSortingPaging” runat=”server” BorderColor=”#999999″ AutoGenerateColumns=”False” BorderWidth=”1px” CellPadding=”4″ ForeColor=”#333333″ GridLines=”None” AllowSorting=”true” AllowPaging=”true” PageSize=”5″ onsorting=”gvSortingPaging_Sorting” onpageindexchanging=”gvSortingPaging_PageIndexChanging”>
    <AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
    <Columns>
        <asp:TemplateField HeaderText=”Id”>
            <ItemTemplate>
                <asp:Label ID=”Label3″ runat=”server” Text='<%# Eval(“id”) %>’></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText=”First  Name” SortExpression=”FullName”>
         <ItemTemplate>
           <asp:Label ID=”Label4″ runat=”server” Text=' <%# Eval(“FullName”) %>’></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText=”Last Name” SortExpression=”LastName”>
            <ItemTemplate>
                <asp:Label ID=”Label1″ Text='<%# Eval(“LastName”) %>’ runat=”server”></asp:Label>
           </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText=”MatchCount” SortExpression=”matchCount”>
           <ItemTemplate>
              <asp:Label ID=”Label2″ runat=”server” Text=' <%# Eval(“matchCount”) %>’></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor=”#999999″ />
    <FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
    <HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
    <PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
    <RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
    <SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
</asp:GridView>
//*

 


Code Behind: step by step for sorting Girdview

//*
protected void Page_Load(object sender, EventArgs e){
 if (!Page.IsPostBack)
 {
    gvSortingPaging.DataSource = populateGridView();
    gvSortingPaging.DataBind();
  }
}

public DataTable populateGridView()
{
    string myQuery = "select id,FullName,LastName,matchCount from myTable";
    SqlDataAdapter dap = new SqlDataAdapter(myQuery, con);
    DataSet ds = new DataSet();
    dap.Fill(ds);
    return ds.Tables[0];
}

protected void gvSortingPaging_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortingDirection = string.Empty;
    if (direction == SortDirection.Ascending)
    {
     direction = SortDirection.Descending;
        sortingDirection = "Desc";
    }
    else
    {
        direction = SortDirection.Ascending;
        sortingDirection = "Asc";
    }
    DataView sortedView = new DataView(populateGridView());
    sortedView.Sort = e.SortExpression + " " + sortingDirection;
    Session["objects"] = sortedView;
    gvSortingPaging.DataSource = sortedView;
    gvSortingPaging.DataBind();
      
}
//*

 

Now here we store the direction in `ViewState` i.e. ( Ascending or Descending for sorting the gridview).

//*
public SortDirection direction
{
    get
    {
        if (ViewState["directionState"] == null)
       {
            ViewState["directionState"] = SortDirection.Ascending;
        }
        return (SortDirection)ViewState["directionState"];
    }
    set
    { ViewState["directionState"] = value; }
}

protected void gvSortingPaging_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvSortingPaging.PageIndex = e.NewPageIndex;
    gvSortingPaging.DataSource = Session["objects"];
    gvSortingPaging.DataBind();
}
//*

 

You must check these articles:

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }


2 comments on “Sorting Gridview control on header click with pagination Asp.net C#”

  1. Mark Cotgrove

    Hi,
    I’ve just had to make a small alteration to get it to work with with me;
    On the gvSortingPaging_PageIndexChanging method I’ve had to change the line
    gvSortingPaging.DataSource = Session[“objects”];
    to
    gvSortingPaging.DataSource = Session[“objects”] ?? PopulateGridView();
    As it may not of been sorted it yet, so the data wouldn’t of been in the session.

    Thanks
    Mark.


Post Comment


Your email address will not be published. Required fields are marked *