Skip to main content

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

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" ...
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

and elsewhere in Page_Load:
if (!IsPostBack)
gv.DataSource = someArray;

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;

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;
PreviousSortExpression = e.SortExpression;

CurrentSortExpression = e.SortExpression;
CurrentSortDirection = e.SortDirection;



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";
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;

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 :)
<cc:GridViewEx ID="gv" runat=server AllowPaging=True AllowSorting=True 
OnDataSourceRequested="gv_DataSourceRequested" AutoGenerateColumns="False">

<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

protected void Page_Load(object sender, EventArgs e)
gv.DataSourceRequest+=new DataSourceRequestEventHandler(gv_DataSourceRequested);
if (!IsPostBack)
protected void gv_DataSourceRequested(out Array dataSource)
dataSource = someArray;

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.

Download source/demo project - 10.5 Kb


Popular posts from this blog

How to merge cells with equal values in the GridView

My solution is not the first; however, I think, it is rather universal and very short - less than 20 lines of the code.

The algorithm is simple: to bypass all the rows, starting from the second at the bottom, to the top. If a cell value is the same as a value in the previous (lower) row, then increase RowSpan and make the lower cell invisible, and so forth.

The code that merges the cells is very short:
public class GridDecorator { public static void MergeRows(GridView gridView) { for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--) { GridViewRow row = gridView.Rows[rowIndex]; GridViewRow previousRow = gridView.Rows[rowIndex + 1]; for (int i = 0; i < row.Cells.Count; i++) { if (row.Cells[i].Text == previousRow.Cells[i].Text) { row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : prev…

Merging columns in GridView/DataGrid header

As necessity to show header columns in a few rows occurs fairly often it would be good to have such functionality in the GridView/DataGrid control as an in-built feature. But meanwhile everyone solves this problem in his own way.

The described below variant of the merging implementation is based on irwansyah's idea to use the SetRenderMethodDelegate method for custom rendering of grid columns header. I guess this approach can be simplified in order to get more compact and handy code for reuse.
The code overview
As it may be required to merge a few groups of columns - for example, 1,2 and 4,5,6 - we need a class to store common information about all united columns.
private class MergedColumnsInfo
// indexes of merged columns
public List<int> MergedColumns = new List<int>();
// key-value pairs: key = the first column index, value = number of the merged columns
public Hashtable StartColumns = new Hashtable();
// key-value pairs: key = the first column in…

JIRA REST API: Cookie-based Authentication

Three authentication methods are proposed by the JIRA REST API documentation: Basic Authentication is a simple but not very safe approach. Credentials are sent in the header on every request and encoding to Base64 is not a proper protection in this case; HTTPS connection is required. OAuth authentication - looks a bit complex and requires additional configuration at the JIRA server that is not always possible. Cookie-based Authentication - this approach seems to be the most convinient one: credentials are checked once, then the authentication cookie only is sent on subsequent requests. However, trying to use the cookie-based authentication I encountered an issue. The approach described in the documentation worked partially: I was able to create a new session and get the response containing the session cookie but all subsequent requests using this session cookie were rejected as unauthorized. Spending some time investigating this I found the cause of the issue: JSESSIONID is not th…