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

/ / 0 Comments
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:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

0 Comments

  1. Satinder singh 09/22/2015 16:42:06
    Hi mark, thanks for the comment. Well inside PopulateGridview() you can explicitly set the session object with default direction (Asc/Desc)