ASP.NET - Gridview sorting HeaderTemplate - Asked By Anandh Ramanujam on 03-Feb-11 11:14 PM

Hi,

How to implement sorting in gridview with HeaderTemplate.

And also I want to add Image in the Header to indicate ascending or descending

Thanks.
Anoop S replied to Anandh Ramanujam on 03-Feb-11 11:20 PM
Refer this example for sorting gridview with header template using Jquery
http://www.tablesorter.com/docs/#Demo
Mihir Soni replied to Anandh Ramanujam on 03-Feb-11 11:39 PM
Hello,
 
here is nice tutorial for that thing

http://zc0000.wordpress.com/2007/10/09/customize-gridviews-header-for-sorting-function/

Hope this helps you
div v replied to Anandh Ramanujam on 03-Feb-11 11:40 PM
hi,

in cs.page:

private void BindGrid()
    {
      int totalRecords;
        
      GridView1.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
      GridView1.DataBind();
        
    }
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      if (e.CommandName.Equals("Sort"))
      {
        if (this.ViewState["SortExp"] == null)
        {
          this.ViewState["SortExp"] = e.CommandArgument.ToString();
          this.ViewState["SortOrder"] = "ASC";
        }
        else
        {
          if (this.ViewState["SortExp"].ToString() == e.CommandArgument.ToString())
          {
            if (this.ViewState["SortOrder"].ToString() == "ASC")
              this.ViewState["SortOrder"] = "DESC";
            else
              this.ViewState["SortOrder"] = "ASC";
 
          }
          else
          {
            this.ViewState["SortOrder"] = "ASC";
            this.ViewState["SortExp"] = e.CommandArgument.ToString();
          }
        }
 
        BindData();
      }
 
 
    }
 
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
      DataTable dataTable = GridView1.DataSource as DataTable;
 
      if (dataTable != null)
      {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
 
        GridView1.DataSource = dataView;
        GridView1.DataBind();
      }
    }
    private string ConvertSortDirectionToSql(SortDirection sortDirection)
    {
      string newSortDirection = String.Empty;
 
      switch (sortDirection)
      {
        case SortDirection.Ascending:
          newSortDirection = "ASC";
          break;
 
        case SortDirection.Descending:
          newSortDirection = "DESC";
          break;
      }
 
      return newSortDirection;
    }
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
      if (e.Row != null && e.Row.RowType == DataControlRowType.Header)
      {
        foreach (TableCell cell in e.Row.Cells)
        {
          if (cell.HasControls())
          {
            LinkButton button = cell.Controls[0] as LinkButton;
            if (button != null)
            {
              Image image = new Image();
              image.ImageUrl = "default.gif";
              if (GridView1.SortExpression == button.CommandArgument)
              {
                if (GridView1.SortDirection == SortDirection.Ascending)
                  image.ImageUrl = "asc.gif";
                else
                  image.ImageUrl = "desc.gif";
              }
              cell.Controls.Add(image);
            }
 
          }
 
        }
 
      }
    }
aspx page:
<asp:GridView ID="GridView1" runat="server"  Width = "100%"
    AutoGenerateColumns = "False" CellPadding="4" AlternatingRowStyle-BackColor = "#EFF3FB" 
    HeaderStyle-BackColor = "#B51032" AllowPaging ="True" AllowSorting="true"   
    OnPageIndexChanging = "OnPaging"
     
        
    BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
        onsorting="GridView1_Sorting" >
       <RowStyle BackColor="White" ForeColor="#330099" />
     <Columns>
     <asp:HyperLinkField DataNavigateUrlFields="UserName" DataNavigateUrlFormatString="UserInformation.aspx?user={0}" Text="Manage" />
       
       <asp:TemplateField HeaderText="User Name" SortExpression="UserName">
       <HeaderTemplate>
         <asp:LinkButton ID="lnkbtnUserName" runat="server" CausesValidation="false" CommandArgument="UserName" CommandName="Sort" ForeColor="#FFFFFF">User Name</asp:LinkButton>
          
      </HeaderTemplate>
        <ItemTemplate>
          <asp:Label runat="server" ID="lblUserName" Text='<%# Eval("UserName") %>'></asp:Label>
        </ItemTemplate>
          
      </asp:TemplateField>
       
        
       
       
        
      <asp:TemplateField HeaderText="Email" SortExpression="Email">
       <HeaderTemplate>
         <asp:LinkButton ID="lnkbtnEmail" runat="server" CausesValidation="false" CommandArgument="Email" CommandName="Sort" ForeColor="#FFFFFF">Email</asp:LinkButton>
         
      </HeaderTemplate>
        <ItemTemplate>
          <asp:Label runat="server" ID="lblEmail" Text='<%# Eval("Email") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox runat="server" ID="Email" Text='<%# Bind("Email") %>'></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="Email" Display="Dynamic"
            ErrorMessage="You must provide an email address." SetFocusOnError="True">*</asp:RequiredFieldValidator>
          <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="Email" Display="Dynamic"
            ErrorMessage="The email address you have entered is not valid. Please fix this and try again."
            SetFocusOnError="True"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
        </EditItemTemplate>
      </asp:TemplateField>
       
       <asp:CheckBoxField DataField="IsApproved" HeaderText="Approved?" />
        <asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" />
        <asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" />
         
      <asp:TemplateField HeaderText="Comment" SortExpression="Comment">
      <HeaderTemplate>
         <asp:LinkButton ID="lnkbtnComment" runat="server" CausesValidation="false" CommandArgument="Comment" CommandName="Sort" ForeColor="#FFFFFF">Comment</asp:LinkButton>
         <asp:PlaceHolder ID="placeholderComment" runat="server"></asp:PlaceHolder>
      </HeaderTemplate>
        <ItemTemplate>
          <asp:Label runat="server" ID="Label2" Text='<%# Eval("Comment") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox runat="server" ID="Comment" TextMode="MultiLine" Columns="40" Rows="4" Text='<%# Bind("Comment") %>'></asp:TextBox>
        </EditItemTemplate>
      </asp:TemplateField>
       
</Columns>
       <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
       <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
       <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
       <HeaderStyle BackColor="#B51032" Font-Bold="True" ForeColor="#FFFFFF" />
  </asp:GridView>
Subhashini Janakiraman replied to Anandh Ramanujam on 03-Feb-11 11:40 PM
You can do sorting in a Gridview easily by making the property AllowSorting to true in the GridView Object.This automatically makes all the Column headers have a hyperlink.On clicking of the hyperlink at runtime it produces sorting numbers or alphabets in ascending order,while double clicking makes it in descending order.