Blue Theme Orange Theme Green Theme Red Theme
 
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » GridView Multicolumn sorting

GridView Multicolumn sorting

GridView's built-in sorting can be enabled by setting a data source and AllowSorting property to true. Click on column header to sort based on the SortExpression specified in the Gridview column. However, Gridview does not support multi column sorting which is required in day to day application. So here is how I tried to create one:

Author Rank:
Total page views :  10248
Total downloads :  188
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewMultiColumnSort.zip
 
Become a Sponsor


GridView Multicolumn sorting

The ASP.NET GridView control is the successor to the v1.x DataGrid, adding the ability to take advantage of specific capabilities of ASP.NET data source controls. Whereas the v1.x DataGrid required a page developer to write custom code to handle simple operations such as paging, sorting, editing or deleting data, the GridView control can automatically handle these operations provided its bound data source control supports these capabilities. The GridView also offers some functionality improvements over the DataGrid, such as the ability to define multiple primary key fields, and some UI customization improvements, such as new field types and templating options. It also exposes a new model for page developers to handle or cancel events. Read more..

GridView's built-in sorting can be enabled by setting a data source and AllowSorting property to true. Click on column header to sort based on the SortExpression specified in the Gridview column. However, Gridview does not support multi column sorting which is required in day to day application.

So here is how I tried to create one-

Create a custom control that will inherit from gridview

public class MCNGridView : GridView

Create properties to enable/disable multicolumn sorting

            
bool _ShowSortSequence = false;
        bool _EnableMultiColumnSorting = false;
        string _SortAscImageUrl = string.Empty;
        string _SortDescImageUrl = string.Empty;
        #region Properties
        /// <summary>
        /// Enable/Disable MultiColumn Sorting.
        /// </summary>
        [
        Description("Sorting On more than one column is enabled or not"),
        Category("Behavior"),
        DefaultValue("false"),
        ]
        public bool EnableMultiColumnSorting
        {
            get { return _EnableMultiColumnSorting; }
            set { AllowSorting = true; _EnableMultiColumnSorting = value; }
        }
        /// <summary>
        /// Enable/Disable Sort Sequence visibility.
        /// </summary>
        [
        Description("Show Sort Sequence or not"),
        Category("Behavior"),
        DefaultValue("false"),
        ]
        public bool ShowSortSequence
        {
            get { return _ShowSortSequence; }
            set { _ShowSortSequence = value; }
        }
        /// <summary>
        /// Get/Set Image for displaying Ascending Sort order.
        /// </summary>
        [
        Description("Image to display for Ascending Sort"),
        Category("Misc"),
        Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
        DefaultValue(""),

        ]
        public string SortAscImageUrl
        {
            get { return _SortAscImageUrl; }
            set { _SortAscImageUrl = value; }
        }
        /// <summary>
        /// Get/Set Image for displaying Descending Sort order.
        /// </summary>
        [
        Description("Image to display for Descending Sort"),
        Category("Misc"),
        Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
        DefaultValue(""),
        ]
        public string SortDescImageUrl
        {
            get { return _SortDescImageUrl; }
            set { _SortDescImageUrl = value; }
        }

Override Gridview OnSorting event

To get the custom sort expression

protected override void OnSorting(GridViewSortEventArgs e)
        {
            if (EnableMultiColumnSorting)
                e.SortExpression = GetSortExpression(e);
            base.OnSorting(e);
        }

Override Gridview OnRowCreated event

To show the sort direction image and sort sequence

protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (SortExpression != String.Empty)
                    ShowSortOrderImages(SortExpression, e.Row);
            }
            base.OnRowCreated(e);
        }


Other protected methods

            
/// <summary>
        ///  Get Sort Expression from existing Grid View Sort Expression
        /// </summary>
        protected string GetSortExpression(GridViewSortEventArgs e)
        {
            string[] sortColumns = null;
            string sortAttribute = SortExpression;
            if (sortAttribute != String.Empty)
            {
                sortColumns = sortAttribute.Split(",".ToCharArray());
            }
            if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression))
                sortAttribute = UpdateSortExpression(sortColumns, e.SortExpression);
            else
                sortAttribute += String.Concat(",", e.SortExpression, " ASC ");
            return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());

        }
        /// <summary>
        ///  Toggle the sort order or remove the column from sort
        /// </summary>
        protected string UpdateSortExpression(string[] sortColumns, string sortExpression)
        {
            string ascSortExpression = String.Concat(sortExpression, " ASC ");
            string descSortExpression = String.Concat(sortExpression, " DESC ");
            for (int i = 0; i < sortColumns.Length; i++)
            {
                if (ascSortExpression.Equals(sortColumns[i]))
                    sortColumns[i] = descSortExpression;
                else if (descSortExpression.Equals(sortColumns[i]))
                    Array.Clear(sortColumns, i, 1);
            }
            return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray());
        }
        /// <summary>
        ///  Lookup the Current Sort Expression to determine the Order of a specific item.
        /// </summary>
        protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo)
        {
            sortOrder = "";
            sortOrderNo = -1;
            for (int i = 0; i < sortColumns.Length; i++)
            {
                if (sortColumns[i].StartsWith(sortColumn))
                {
                    sortOrderNo = i + 1;
                    if (EnableMultiColumnSorting)
                        sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim();
                    else
                        sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC");
                }
            }
        }
        /// <summary>
        ///  Show an image for the Sort Order with sort sequence no.
        /// </summary>
        protected void ShowSortOrderImages(string sortExpression, GridViewRow dgItem)
        {
            string[] sortColumns = sortExpression.Split(",".ToCharArray());

            for (int i = 0; i < dgItem.Cells.Count; i++)
            {
                if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
                {
                    string sortOrder;
                    int sortOrderNo;
                    string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
                    SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo);
                    if (sortOrderNo > 0)
                    {
                        string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl);
 
                        if (sortImgLoc != String.Empty)
                        {
                            Image imgSortDirection = new Image();
                            imgSortDirection.ImageUrl = sortImgLoc;
                            dgItem.Cells[i].Controls.Add(imgSortDirection);
                            if (EnableMultiColumnSorting && _ShowSortSequence)
                            {
                                Label lblSortOrder = new Label();
                                lblSortOrder.Font.Size = FontUnit.XSmall;
                                lblSortOrder.Font.Name = "verdana";
                                lblSortOrder.Text = sortOrderNo.ToString();
                                dgItem.Cells[i].Controls.Add(lblSortOrder);
                            }
                        }
                        else
                        {
                            Label lblSortDirection = new Label();
                            lblSortDirection.Font.Size = FontUnit.XSmall;
                            lblSortDirection.Font.Name = "verdana";
                            lblSortDirection.EnableTheming = false;
                            lblSortDirection.Text = (sortOrder.Equals("ASC") ? "^" : "v");
                            dgItem.Cells[i].Controls.Add(lblSortDirection);
                            if (EnableMultiColumnSorting && _ShowSortSequence)
                            {
                                Literal litSortSeq = new Literal();
                                litSortSeq.Text = sortOrderNo.ToString();
                                dgItem.Cells[i].Controls.Add(litSortSeq);
                            }
                        }
                    }
                }
            }
        }

On Aspx page

Register the control

<%@ Register Assembly="MCNGridView" namespace="MCNGridView" tagprefix="MCN" %>

Create the grid and bind the data

<MCN:MCNGridView ID="MCNGridView1" runat="server" EnableMultiColumnSorting="True"       
        AutoGenerateColumns="False" DataKeyNames="CustomerID"  ShowSortSequence="True"
        DataSourceID="SqlDataSource1" CellPadding="4"
        ForeColor="#333333" GridLines="None" AllowPaging="True"
        SortAscImageUrl="~/Images/asc.png" SortDescImageUrl="~/Images/desc.png">
        <RowStyle BackColor="#EFF3FB" />
        <Columns>
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
                SortExpression="CustomerID">
            </asp:BoundField>
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
                SortExpression="CompanyName" />
            <asp:BoundField DataField="ContactName" HeaderText="ContactName"
                SortExpression="ContactName" />
            <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"
                SortExpression="ContactTitle" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            <asp:BoundField DataField="Region" HeaderText="Region"
                SortExpression="Region" />
            <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
                SortExpression="PostalCode" />
            <asp:BoundField DataField="Country" HeaderText="Country"
                SortExpression="Country" />
        </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
    </MCN:MCNGridView>

Thats all you are ready with Multicolumn sorting in Gridview.


Login to add your contents and source code to this article
 About the author
 
Nipun Tomar
Nipun has 5 years working experience in .NET technologies. He holds Bachelor's and Master's degree in Computer Science. Currently working on ASP.NET 2.0/3.5, VB.NET, C#.NET, AJAX, SQL Server 2005, WPF, WCF and Silverlight.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewMultiColumnSort.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor
 Comments
problem applying filters by STEVE On September 22, 2009

Looks great, but I can only get it to filter 1 column, the others don't change when the filters are applied.  Any thoughts on what I'm doing wrong?

Reply | Email | Delete | Modify | 
Nice article by adil On October 19, 2009
Best for those who are looking for extending GridView.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.