5,427,303 members and growing! (15,835 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

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

By Mykola Tarasyuk

The article describes how to implement paging and sorting for the GridView control that works with the array of the objects.
C# 2.0, C#, Windows, .NET, .NET 2.0, ASP.NET, VS2005, Visual Studio, Dev

Posted: 17 Mar 2007
Updated: 17 Mar 2007
Views: 26,187
Bookmarked: 29 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
12 votes for this Article.
Popularity: 4.07 Rating: 3.77 out of 5
1 vote, 8.3%
1
1 vote, 8.3%
2
1 vote, 8.3%
3
2 votes, 16.7%
4
7 votes, 58.3%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Screenshot - gridviewex.gif

Introduction

Fairly often the such data presentation model is used: the array of objects is bound to the GridView control with the predefined columns. Its model is popularized by the DotNetNuke web framework and has the advantage of work with the business objects instead of the nameless rows of the 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 build-in ability for sorting and paging if it is bound to the array of the 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 sorting event handler but it does not save information about previous sorting state. So I add a few variables to save the data: PreviousSortExpression, CurrentSortExpression, 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 someting is lacking. There is none visual presentation whether grid is sorted and how it is sorted. So I change sorted column header to show this information. I do it by the 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 of 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 user sorts grid or changes the current page of the data. 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 specified property in specified order(Ascending or Descending).

How to use it

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

<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 that you need to use this control, no additional work for paging or sorting use is required.
The full code you can find 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

About the Author

Mykola Tarasyuk


I am working as software developer in Ukraine, mainly making web-based applications using ASP.Net. My personal site on web development: Casual ideas for web development

Occupation: Web Developer
Location: Ukraine Ukraine

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
Subject  Author Date 
Questionnative SqlDataSource of GridviewmemberCyNETT6:48 16 Jul '08  
AnswerRe: native SqlDataSource of GridviewmemberMykola Tarasyuk10:31 16 Jul '08  
GeneralQuestionmembercontini5:47 9 Apr '08  
GeneralRe: Question [modified]memberMykola Tarasyuk8:46 9 Apr '08  
GeneralRe: Questionmembercontini1:22 10 Apr '08  
GeneralRe: QuestionmemberMykola Tarasyuk7:04 10 Apr '08  
GeneralRe: Questionmembercontini3:31 11 Apr '08  
GeneralRe: QuestionmemberMykola Tarasyuk7:16 11 Apr '08  
GeneralThanks for the controlmemberMember 27980349:17 9 Mar '08  
QuestionFancy triangles in compact framework?memberscoroop4:18 3 Aug '07  
AnswerRe: Fancy triangles in compact framework?memberMykola Tarasyuk8:11 3 Aug '07  
GeneralThanks! [modified]memberdarshan arney8:43 27 Jul '07  
GeneralSorting on aggregate element.memberMassimo Ugues7:04 17 Jul '07  
AnswerRe: Sorting on aggregate element.memberMykola Tarasyuk21:25 18 Jul '07  
GeneralRe: Sorting on aggregate element.memberMassimo Ugues1:19 23 Aug '07  
QuestionHi'memberturbochris12:28 23 Apr '07  
AnswerRe: Hi'memberMykola Tarasyuk22:56 24 Apr '07  
GeneralRe: Hi'memberturbochris16:09 25 Apr '07  
GeneralRe: Hi'memberMykola Tarasyuk20:42 25 Apr '07  
GeneralRe: Hi'memberMykola Tarasyuk5:54 27 Apr '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Mar 2007
Editor:
Copyright 2007 by Mykola Tarasyuk
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project