Gridview - Multi-column sorting

venkatesh padmanabhan 181 Reputation points
2022-09-09T10:22:51.597+00:00

Hi.
I am using VS 2017 and ASP.NET C# website. I am trying to achieve multi column sorting in Gridview ? I have added allowsorting to true and added sortexpression on all BoundField columns. However, the sorting does not work on multiple columns. Below is the code used . How to fix this?

<div class="table-responsive">  
                        <asp:GridView ID="grdSearch" runat="server"   
                            GridLines="Both" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true"  
                            PageSize="25" OnPageIndexChanging="grdSearch_PageIndexChanging"   >                             
                            <EmptyDataTemplate>No Records Available</EmptyDataTemplate>  
                            <Columns>  
                                <asp:BoundField DataField="Description" SortExpression="Description" HeaderText="Class" />  
                                <asp:BoundField DataField="DK1" SortExpression="DK1" HeaderText="Key 1" ItemStyle-Width="100px" ItemStyle-Wrap="true" />  
                                <asp:BoundField DataField="DK2" SortExpression="DK2" HeaderText="Key 2" ItemStyle-Width="100px" ItemStyle-Wrap="true" />  
                                <asp:BoundField DataField="DK3" SortExpression="DK3" HeaderText="Key 3" ItemStyle-Width="100px" ItemStyle-Wrap="true" />                            
                    
                                <asp:TemplateField>  
                                    <ItemTemplate>  
                                        <asp:HyperLink ID="lnkEdit" runat="server"  
                                            NavigateUrl='link'  
                                            Target="_blank"  
                                            Text='View Image'                                             
                                        </asp:HyperLink>  
                                    </ItemTemplate>  
                                </asp:TemplateField>                                 
                            </Columns>  
                        </asp:GridView>  
                    </div>                
            </ContentTemplate>  
        </asp:UpdatePanel>  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,251 questions
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 1,906 Reputation points
    2022-09-10T01:50:18.607+00:00

    You have to use the data source control with the GridView such as the SqlDataSource and ObjectDataSoure to enable sorting.

    Otherwise you will have to write the code to enable sorting by yourself. Shown blow is sample:

    .aspx.cs

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
    using System.Data;  
       
    public partial class _0055_GridViewSorting : System.Web.UI.Page  
    {  
        // Create DataView as data source of GridView  
        protected DataView CreateDataSource()  
        {  
            DataTable dt = new DataTable();  
            DataRow dr;  
       
            dt.Columns.Add(new DataColumn("ID", typeof(Int32)));  
            dt.Columns.Add(new DataColumn("Name", typeof(string)));  
            dt.Columns.Add(new DataColumn("Type", typeof(string)));  
            dt.Columns.Add(new DataColumn("Price", typeof(Int32)));  
            dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));  
            dt.Columns.Add(new DataColumn("Amount", typeof(Int32)));  
            dt.Columns.Add(new DataColumn("CatID", typeof(Int32)));  
            dt.Columns.Add(new DataColumn("Note", typeof(string)));  
            dt.Columns.Add(new DataColumn("Disc", typeof(bool)));  
            dt.Columns.Add(new DataColumn("Date", typeof(DateTime)));  
       
            for (int i = 0; i < 15; i++)  
            {  
                dr = dt.NewRow();  
                dr["ID"] = i;  
                dr["Name"] = "Product Name_" + i.ToString();  
                dr["Type"] = "Product Type " + (100 - i).ToString();  
                dr["Price"] = 123000 * (i + 1);  
                dr["Qty"] = (i + 1) * 20;  
                dr["Amount"] = 123000 * (i + 1) * (i + 1);  
                dr["CatID"] = 100 - i;  
                dr["Note"] = "Note_" + i.ToString();  
                dr["Disc"] = (i % 2 == 0) ? true : false;  
                dr["Date"] = DateTime.Now.AddDays(i);  
                dt.Rows.Add(dr);  
            }  
            return new DataView(dt);  
        }  
       
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!Page.IsPostBack)  
            {  
                GridView1.DataSource = CreateDataSource();  
                GridView1.DataBind();  
            }  
        }  
       
        protected void GridView1_Sorting(object sender,   
                                          GridViewSortEventArgs e)  
        {  
            GridView gv = (GridView)sender;  
            DataView view = CreateDataSource();  
            string exp = e.SortExpression;  
       
            // switch ASC / DESC when same LinkButton is clicked  
            if (gv.Attributes["CurrentSortField"] != null &&  
                gv.Attributes["CurrentSortDir"] != null)  
            {  
                if (exp == gv.Attributes["CurrentSortField"])  
                {  
                    if (gv.Attributes["CurrentSortDir"] == "ASC")  
                    {  
                        exp = exp + " DESC";  
                        gv.Attributes["CurrentSortDir"] = "DESC";  
                    }  
                    else  
                    {  
                        exp = exp + " ASC";  
                        gv.Attributes["CurrentSortDir"] = "ASC";  
                    }  
                }  
                else  
                {  
                    gv.Attributes["CurrentSortField"] = exp;  
                    exp = exp + " ASC";  
                    gv.Attributes["CurrentSortDir"] = "ASC";  
                }  
            }  
       
            view.Sort = exp;  
            gv.DataSource = view;  
            gv.DataBind();  
        }  
    }  
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true"   
        CodeFile="0055-GridViewSorting.aspx.cs"   
        Inherits="_0055_GridViewSorting" %>  
       
    <!DOCTYPE html>  
       
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title></title>  
    </head>  
    <body>  
        <form id="form1" runat="server">  
            <asp:GridView ID="GridView1" runat="server"  
                AllowSorting="True"  
                CurrentSortField=""  
                CurrentSortDir=""  
                onsorting="GridView1_Sorting">  
            </asp:GridView>  
        </form>  
    </body>  
    </html>  
    

    Result

    239687-image2.jpg

    0 comments No comments

  2. Lan Huang-MSFT 25,471 Reputation points Microsoft Vendor
    2022-09-13T06:18:13.943+00:00

    Hi @venkatesh padmanabhan ,
    You need to use gridView.Sorting Event:Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.
    https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridview.sorting?view=netframework-4.8
    You can refer to the example in the official documentation.

    protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)  
      {  
      
        //Retrieve the table from the session object.  
        DataTable dt = Session["TaskTable"] as DataTable;  
      
        if (dt != null)  
        {  
      
          //Sort the data.  
          dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);  
          TaskGridView.DataSource = Session["TaskTable"];  
          TaskGridView.DataBind();  
        }  
      
      }  
      
      private string GetSortDirection(string column)  
      {  
      
        // By default, set the sort direction to ascending.  
        string sortDirection = "ASC";  
      
        // Retrieve the last column that was sorted.  
        string sortExpression = ViewState["SortExpression"] as string;  
      
        if (sortExpression != null)  
        {  
          // Check if the same column is being sorted.  
          // Otherwise, the default value can be returned.  
          if (sortExpression == column)  
          {  
            string lastDirection = ViewState["SortDirection"] as string;  
            if ((lastDirection != null) && (lastDirection == "ASC"))  
            {  
              sortDirection = "DESC";  
            }  
          }  
        }  
      
        // Save new values in ViewState.  
        ViewState["SortDirection"] = sortDirection;  
        ViewState["SortExpression"] = column;  
      
        return sortDirection;  
      }  
          
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments