Click here to Skip to main content
13,140,613 members (51,452 online)
Click here to Skip to main content
Add your own
alternative version


45 bookmarked
Posted 5 Aug 2004

Sorting DataGrid programmatically

, 5 Aug 2004
Rate this:
Please Sign up or sign in to vote.
This code sorts a Windows.Forms.DataGrid programmatically, "emulating" a header click.


This article shows, how to programmatically sort a System.Windows.Forms.DataGrid. In other words, how to emulate a "click" on a column header.

Typically, to sort a DataGrid, we call the DataView.Sort method of an underlying DataView. But what if our DataGrid is bound to a custom datasource? In this case, there's no DataView under our DataGrid!


I was writing an application and the task was to "remember" the way DataGrids are sorted. So I needed to save my sortings to the Windows registry and restore it each time my application starts.

The problem was: my DataGrid was bound to a custom collection, no DataViews or DataTables.

Sorting Basics

If your DataGrid is bound to some IList collection and you want your DataGrid to support sorting - your collection must implement IBindingList interface. This interface contains a method ApplySort() among others. When a user clicks a column header, DataGrid calls the datasource's method ApplySort().

ApplySort() method takes two arguments: property and direction.

void IBindingList.ApplySort(PropertyDescriptor property, 
                                           ListSortDirection direction)

Each column of your DataGrid represents some property of an underlying object. And you have to pass this property to ApplySort() method.

Emulate column header click

I've discovered that simply calling ApplySort() doesn't work. Calling DataGrid's OnMouseDown() protected method with MouseEventArgs pointed to a column header also doesn't work!

So, I used System.Reflection to look deep inside the DataGrid class and see what happens when a user clicks a header. In the list of DataGrid's private members, I've found a private method ColumnHeaderClicked(). See what I mean? Bingo.

This method is defined as follows:

private void ColumnHeaderClicked(PropertyDescriptor prop)

So, if we want to sort column number 5, we have to determine the underlying PropertyDescriptor for this column and pass this PropertyDescriptor to ColumnHeaderClicked method. This can be done in two ways.

  • Calling for a GridColumnStyle.PropertyDescriptor property of a grid column. But this property sometimes returns null if our grid is bound to a custom collection through MappingNames.
  • If our DataGrid is bound to a custom collection MyCollection, we typically create a TableStyle and some GridColumnStyles and assign its MappingNames. TableStyle's MappingName would be "MyCollection" and ColumnStyle's MappingName would contain the name of some property this column displays. So, we can get the PropertyDescriptor object by seeking for the property with the name, equal to the column's MappingName.

After we have a PropertyDescriptor object, we simply invoke a private method using System.Reflection.

Now the code:

public class MyDataGrid : DataGrid
 //sort a column by its index
 public void SortColumn(int columnIndex)
  if(this.DataSource!=null && 
   //discover the TYPE of underlying objects
   Type sourceType = ((System.Collections.IList)this.DataSource)[0].GetType();

   //get the PropertyDescriptor for a sorted column
   //assume TableStyles[0] is used for our datagrid... (change it if necessary)
   System.ComponentModel.PropertyDescriptor pd =

   //if the above line of code didn't work try to get a propertydescriptor
   // via MappingName
   if(pd == null)
    System.ComponentModel.PropertyDescriptorCollection pdc =
    pd =
     pdc.Find( this.TableStyles[0].GridColumnStyles[columnIndex].MappingName, 

   //now invoke ColumnHeaderClicked method using system.reflection tools
   System.Reflection.MethodInfo mi =
     System.Reflection.BindingFlags.Instance |
   mi.Invoke(this, new object[] { pd });

That's it.


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

Alex Yumas
Founder Jitbit
United Kingdom United Kingdom
I'm CEO/Founder and lead developer at Jitbit Software

You may also be interested in...

Comments and Discussions

GeneralMy vote of 3 Pin
sangar202018-Dec-12 1:26
membersangar202018-Dec-12 1:26 
GeneralWindows.Forms.DataGrid.DataSource.DefaultView.Sort Pin
pcflasch28-Mar-07 10:59
memberpcflasch28-Mar-07 10:59 
GeneralMultiple Sorting on Columns Pin
RakshitUppal21-May-06 12:22
memberRakshitUppal21-May-06 12:22 
GeneralWhy calling private Methods? No need to do that... Pin
fex1346-Oct-05 23:35
memberfex1346-Oct-05 23:35 
GeneralRe: Why calling private Methods? No need to do that... Pin
basskeeper21-Mar-06 1:34
memberbasskeeper21-Mar-06 1:34 
QuestionWhy is "ApplySort" firing twice? Pin
Chris Simeone18-May-05 6:08
memberChris Simeone18-May-05 6:08 
GeneralAnother way - setting sort order for any DataGrid through Currency Manager private method Pin
Alexander Glebovsky17-Apr-05 3:29
sussAlexander Glebovsky17-Apr-05 3:29 
GeneralRe: Another way - setting sort order for any DataGrid through Currency Manager private method Pin
Anonymous4-May-05 1:51
sussAnonymous4-May-05 1:51 
GeneralNo need to subclass DataGrid Pin
Anonymous20-Mar-05 2:54
sussAnonymous20-Mar-05 2:54 
QuestionNe rabotaet nichego. Property descriptor poluchil normalno. Cho delat ? Pin
Anonymous1-Nov-04 3:26
sussAnonymous1-Nov-04 3:26 
AnswerRe: Ne rabotaet nichego. Property descriptor poluchil normalno. Cho delat ? Pin
Anonymous1-Nov-04 3:28
sussAnonymous1-Nov-04 3:28 
GeneralTrouble using code Pin
ElNoNo20-Oct-04 5:22
memberElNoNo20-Oct-04 5:22 
GeneralRe: Trouble using code Pin
ElNoNo20-Oct-04 10:45
memberElNoNo20-Oct-04 10:45 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 6 Aug 2004
Article Copyright 2004 by Alex Yumas
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid