AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=666&pId=-1
Extending the GridView's Sorting Capabilities
page
by souri challa
Feedback
Average Rating: 
Views (Total / Last 10 Days): 62522/ 133

Introduction

[Download Code]

The GridView control is an important addition to the new set of server controls shipped with ASP.NET version 2.0.  Introduced as a successor to the DataGrid in ASP.NET version 1.x, this control declaratively handles the common chores of data binding, sorting, paging, etc., without any need to write code.  GridView achieves this by taking advantage of the new data source controls that also ship with ASP.NET version 2.0.  A number of useful GridView examples may be found at http://beta.asp.net/quickstart/aspnet/doc/ctrlref/data/gridview.aspx

GridView's built-in sorting can be enabled by simply setting its AllowSorting property to true and setting its DataSourceId property to a data source control that supports sorting.

Here is an example declaration that sets up automatic sorting for a GridView control.

Listing 1

<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1"
    DataKeyNames="au_id" AutoGenerateColumns="False" AllowSorting="true"
    PageSize="6" Runat="Server">
    <Columns>
        <asp:BoundField ReadOnly="true" HeaderText="au_id" DataField="au_id"
            SortExpression="au_id"></asp:BoundField>
        <asp:BoundField HeaderText="au_lname" DataField="au_lname"
            SortExpression="au_lname"></asp:BoundField>
        <asp:BoundField HeaderText="city" DataField="city"
            SortExpression="city"></asp:BoundField>
        <asp:BoundField HeaderText="state" DataField="state"
            SortExpression="state"></asp:BoundField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" SelectCommand="SELECT * FROM [authors]"
    ConnectionString="<%$ConnectionStrings:AppConnectionString1 %>"
    Runat="Server">
</asp:SqlDataSource>

This enables sorting on the GridView columns that have a SortExpression specified.  Clicking on the column header link toggles the sort direction.  However, the standard GridView control does not present any visual cues for the sort direction (ascending or descending) and does not support sorting on more than one column (which is not an uncommon need when presenting data across multiple pages).

In this article we will look at extending the GridView server control to provide these desired features, without any need to write code at the page level.

Note: The code for multiple-column sorting is based on a previously published article for ASP.NET version 1.x.  Here we'll examine how to retrofit this code into a server control while making a few enhancements along the way.

Adding New Properties to the Custom GridView

[Download Code]

Before we extend the control, let us determine the new properties we would like to have in the control.

  • AllowMultipleColumnSorting: When set to true, this should enable sorting on more than one column.
  • SortAscImageUrl and SortDescImageUrl: These properties allow the page developer to optionally select an image for indicating the sort direction in the column header.  When these properties are left blank, the control inserts a glyph symbol to indicate the sort direction.  We would like to enable the sort direction indicator for default (single-column) sort behavior, too.

The following code block shows how we define the new properties.

Listing 2

        /// <summary>
        /// Enable/Disable MultiColumn Sorting.
        /// </summary>
        [
        Description("Whether Sorting On more than one column is enabled"),
        Category("Behavior"),
        DefaultValue("false"),
        ]
        public bool AllowMultiColumnSorting
        {
            get
            {
                object o = ViewState["EnableMultiColumnSorting"];
                return (o != null ? (bool)o : false);
            }
            set
            {
                AllowSorting = true; //Set default Sort property to true
                ViewState["EnableMultiColumnSorting"] = value;
            }
        }


        /// <summary>
        /// Get or Set Image location to be used to display 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
            {
                object o = ViewState["SortImageAsc"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["SortImageAsc"] = value;
            }
        }
        /// <summary>
        /// Get or Set Image location to be used to display Ascending 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
            {
                object o = ViewState["SortImageDesc"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["SortImageDesc"] = value;
            }
        }

The design-time attributes for the properties are worth noting.  The Category, Description, and DefaultValue attributes allocate the properties to the corresponding classification in the IDE's Property Browser. The Editor attribute enables a URL Editor for easily choosing the image location.

Overriding GridView Methods

[Download Code]

To implement multiple-column sorting and provide visual indication of the sort direction, we need to override the two methods that invoke the Sorting and RowCreated events.

The first method is OnSorting, which is called whenever a column is sorted.  We simply check to see if the custom property AllowMultiColumnSorting is set to true and, if so, call upon a custom method that gives us the multiple-column sort expression.

It is worth noting that we don't need to do anything special to remember the sort expression between page postbacks.  This is built into the GridView implementation and its SortExpression property stores the last-used sort expression.  Likewise, just by trapping the OnSorting method and changing the SortExpression in the event argument, we're letting GridView fire the Sorting event with the new multiple-column sort expression and passing it to the DataView exposed by the data source control.

Listing 3

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

Next, we override the virtual method OnRowCreated, and set up a visual indicator in the header row for the sort direction.

 

Listing 4

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

Note that in the above-mentioned ASP.NET 1.x article, we had to implement this logic within the ItemDataBound and SortCommand event handlers at the page level.  Here, due to the added capabilities of the GridView control, we are able to shift the logic into the control's implementation.  This enables a no-code implementation (other than declarative syntax) at the page level and simplifies reuse.

Protected Methods

[Download Code]

The following protected methods implement the logic necessary to manipulate the sort expression: GetSortExpression, ModifySortExpression, and SearchSortExpression.

Essentially, we formulate a multiple-column sort expression that can be readily provided to the DataView for sorting.  The multiple-column sort expression is manipulated in the above methods by first breaking up the sort expression into a string array of individual column names.

Full source code for the above methods can be found in the downloadable sample.

DisplaySortOrderImages is the method that displays an image or a glyph (when no images are provided) next to the link in the header of sorted columns.

Using the Extended GridView Control on a Web Form

[Download Code]

Once the above control is compiled, all we need to do is to register the control with the page on which it will be used, place the control on the page, and set its new properties.

Here is an example.

Listing 5

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix=sk Namespace=skcontrols Assembly=skcontrols %>
<html>
<head runat="server">
    <title>Sortable Grid View</title>
</head>
<body>
    <form id="form1" Runat="Server">
        <sk:myGridView ID=gdSort  AllowMultiColumnSorting="true" Runat="Server"
            DataSourceID="SqlDataSource1" PageSize="6"
            SortDescImageUrl="~/Images/sortdescending.gif"
            SortAscImageUrl="~/Images/sortascending.gif">
            <Columns>
                <asp:BoundField ReadOnly="true" HeaderText="au_id"
                    DataField="au_id" SortExpression="au_id">
                 ………………..
            </Columns>
       </sk:myGridView>
       <asp:SqlDataSource ID="SqlDataSource1" Runat="Server"
            SelectCommand="SELECT * FROM [authors]"
            ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">
       </asp:SqlDataSource>
    </form>

Conclusion

[Download Code]

In this article we have examined how to extend the GridView server control to enable multiple-column sorting, by adding an AllowMultipleColumnSorting property.  This extended control also displays an image or glyph in the column header to indicate sort direction (ascending or descending).

The downloadable source code has a server control project and a web application project to test the server control.  The test Web Form uses the Pubs database in Microsoft SQL Server.  Be sure to change the connection string accordingly.


Product Spotlight
Product Spotlight 

©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-01-18 3:36:37 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search