Click here to Skip to main content
11,583,865 members (65,113 online)
Click here to Skip to main content

Implementation of paging and sorting for the GridView control that works with an array of objects

, 16 Mar 2007 72.6K 531 44
Rate this:
Please Sign up or sign in to vote.
The article describes how to implement paging and sorting for the GridView control that works with an array of objects.

Screenshot - gridviewex.gif

Introduction

Fairly often, such a data presentation model is used: an array of objects is bound to a GridView control with predefined columns. This model was popularized by the DotNetNuke web framework and has the advantage of working with the business objects instead of nameless rows of a data table. A classic example:

<asp:GridView id="gv" runat="server" AutoGenerateColumns="False" ...
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"  />
        ... 
    </Columns>
</asp:GridView>

and elsewhere in Page_Load:

if (!IsPostBack)
{
    gv.DataSource = someArray;
    gv.DataBind();
}

A pretty good model, in my opinion. But, the GridView control does not have built-in ability for sorting and paging if it is bound to an array of objects. Let's implement it.

The code overview

I inherit my control from the GridView control and override the OnInit method in order to add two event handlers.

this.PageIndexChanging += new GridViewPageEventHandler(BaseGridView_PageIndexChanging);
this.Sorting += new GridViewSortEventHandler(BaseGridView_Sorting);

The paging implementation is trivial.

void BaseGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     this.PageIndex = e.NewPageIndex;
     BindDataSource();
}

The sorting one is rather complicated. The GridView control has a sorting event handler, but it does not save information about the previous sorting state. So, I added a few variables to save the data: PreviousSortExpression, CurrentSortExpression, and CurrentSortDirection.

void BaseGridView_Sorting(object sender, GridViewSortEventArgs e)
{
      //for unknown reason e.SortExpression always is Ascending
      if (PreviousSortExpression == e.SortExpression)
      {
          e.SortDirection = SortDirection.Descending;
          PreviousSortExpression = null;
      }
      else
          PreviousSortExpression = e.SortExpression;

     CurrentSortExpression = e.SortExpression;
     CurrentSortDirection = e.SortDirection;
     ChangeHeaders(this.HeaderRow);
     BindDataSource();
}

A little something is lacking. There is no visual presentation whether the grid is sorted and how it is sorted. So, I change the sorted column header to show this information. I do it by means of two Unicode symbols: the up arrow (\u25bc) and the down arrow (\u25b2).

private void ChangeHeaders(GridViewRow headerRow)
{
    for (int i = 0; i < headerRow.Cells.Count; i++)
    {
        if (headerRow.Cells[i] is DataControlFieldCell)
        {
            DataControlField field = 
              ((DataControlFieldCell)headerRow.Cells[i]).ContainingField;

            //remove all previous sorting marks if they exist
            Regex r = new Regex(@"\s(\u25bc|\u25b2)");
            field.HeaderText = r.Replace(field.HeaderText, "");

            if (field.SortExpression != null && field.SortExpression == 
                CurrentSortExpression)
            {
                //add current sorting state mark
                if (CurrentSortDirection == SortDirection.Ascending)
                    field.HeaderText += " \u25b2";
                else
                    field.HeaderText += " \u25bc";
            }
        }
    }
}

Now, about filling the grid with data. I add the event that occurs when the data source is requested and the method that will handle this event.

public delegate void DataSourceRequestedEventHandler(out Array dataSource);
public event DataSourceRequestedEventHandler DataSourceRequested;

Refilling of the grid occurs when a user sorts the grid or changes the current page. For initial filling, the BindDataSource method is used.

public void BindDataSource()
{
    Array dataSource = null;
  
    //request for the data source
    if (DataSourceRequested != null)
       DataSourceRequested(out dataSource);
    
    if (dataSource == null)  
       throw new Exception("Failed to get data source.");   

    //sort the data in case of need
    if (CurrentSortExpression != null)
    {
        ArrayList ar = new ArrayList(dataSource);
        ar.Sort(new ArrayComparer(CurrentSortExpression, 
                                  CurrentSortDirection));
        dataSource = ar.ToArray();
    }
   
    base.DataSource = dataSource;
    base.DataBind();
}

ArrayComparer is the implementation of the IComparer interface to compare two objects by a specified property in a specified order (ascending or descending).

How to use it

First of all, because I hide all the paging and sorting functionality inside the new control, I have to reject the old data binding method explicitly. So, I add an event handler for all requests for the data source and the method to call the data binding. And also, it is needed to allow paging and sorting in the GridView Smile | :)

<cc:GridViewEx ID="gv" runat="server" AllowPaging=True AllowSorting=True 
        OnDataSourceRequested="gv_DataSourceRequested" 
        AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"  />
        ... 
    </Columns>>

That is all you need to use this control, no additional work for paging or sorting is required. The full code can be found in the above demo.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Mykola Tarasyuk
Software Developer (Senior)
Ukraine Ukraine
I am a software developer from Ukraine. In my spare time (this means "very rarely last years"), I am blogging about ASP.Net and web development.


You may also be interested in...

Comments and Discussions

 
Questionnative SqlDataSource of Gridview Pin
CyNETT16-Jul-08 5:48
memberCyNETT16-Jul-08 5:48 
AnswerRe: native SqlDataSource of Gridview Pin
Mykola Tarasyuk16-Jul-08 9:31
memberMykola Tarasyuk16-Jul-08 9:31 
GeneralQuestion Pin
contini9-Apr-08 4:47
membercontini9-Apr-08 4:47 
GeneralRe: Question [modified] Pin
Mykola Tarasyuk9-Apr-08 7:46
memberMykola Tarasyuk9-Apr-08 7:46 
GeneralRe: Question Pin
contini10-Apr-08 0:22
membercontini10-Apr-08 0:22 
GeneralRe: Question Pin
Mykola Tarasyuk10-Apr-08 6:04
memberMykola Tarasyuk10-Apr-08 6:04 
Hi Enzo,

It is not the same but it will work. The only moment you have to take into account that if you will decide to add event handlers for Sorting or PageIndexChanging events in order to implement additional functionality - none of these event handlers will be executed.
But if you know where you going to use this grid - your method will work well.

If you are interested I can recommend you very handy and powerful tool - Reflector for .NET. It allows to know how ASP.Net controls are made and what functionality you may change if you override something.

Kind regards,
Mykola
GeneralRe: Question Pin
contini11-Apr-08 2:31
membercontini11-Apr-08 2:31 
GeneralRe: Question Pin
Mykola Tarasyuk11-Apr-08 6:16
memberMykola Tarasyuk11-Apr-08 6:16 
GeneralThanks for the control Pin
Member 27980349-Mar-08 8:17
memberMember 27980349-Mar-08 8:17 
QuestionFancy triangles in compact framework? Pin
scoroop3-Aug-07 3:18
memberscoroop3-Aug-07 3:18 
AnswerRe: Fancy triangles in compact framework? Pin
Mykola Tarasyuk3-Aug-07 7:11
memberMykola Tarasyuk3-Aug-07 7:11 
GeneralThanks! [modified] Pin
darshan arney27-Jul-07 7:43
memberdarshan arney27-Jul-07 7:43 
GeneralSorting on aggregate element. Pin
Massimo Ugues17-Jul-07 6:04
memberMassimo Ugues17-Jul-07 6:04 
AnswerRe: Sorting on aggregate element. Pin
Mykola Tarasyuk18-Jul-07 20:25
memberMykola Tarasyuk18-Jul-07 20:25 
GeneralRe: Sorting on aggregate element. Pin
Massimo Ugues23-Aug-07 0:19
memberMassimo Ugues23-Aug-07 0:19 
QuestionHi' Pin
turbochris23-Apr-07 11:28
memberturbochris23-Apr-07 11:28 
AnswerRe: Hi' Pin
Mykola Tarasyuk24-Apr-07 21:56
memberMykola Tarasyuk24-Apr-07 21:56 
GeneralRe: Hi' Pin
turbochris25-Apr-07 15:09
memberturbochris25-Apr-07 15:09 
GeneralRe: Hi' Pin
Mykola Tarasyuk25-Apr-07 19:42
memberMykola Tarasyuk25-Apr-07 19:42 
GeneralRe: Hi' Pin
Mykola Tarasyuk27-Apr-07 4:54
memberMykola Tarasyuk27-Apr-07 4:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 17 Mar 2007
Article Copyright 2007 by Mykola Tarasyuk
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid