Click here to Skip to main content
15,883,901 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF DataGrid: Enable standard sorting of nullable types on autogenerated columns

Rate me:
Please Sign up or sign in to vote.
4.29/5 (8 votes)
14 Oct 2013CPOL 19.5K   3   3
DataGrid does not sort a nullable value type on an autogenerated column.

Introduction

It's quite common to bind a WPF DataGrid to data using autogenerated columns. It's equally common to have bound properties of a nullable type (ie  Nullable<int>) . However DataGrid does not provide the standard sorting behaviour for nullable types, the column header is not highlighted and clicking has no action. 

Background  

The culprit is the DataGridColumn.CreateDefaultColumn(ItemPropertyInfo) method: It tests the bound property type for IComparable, int inherits from IComparable, but not int? and therefore DataGridColumn .CanUserSort is set to false. 

Using the code 

The remedy is simple, attach this handler to the DataGrid.AutoGeneratingColumn event: 

C#
void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (!e.Column.CanUserSort)
    {
        Type type = e.PropertyType;
        if (type.IsGenericType && type.IsValueType && typeof(IComparable).IsAssignableFrom(type.GetGenericArguments()[0]))
        {
            // allow nullable primitives to be sorted
            Debug.Assert(type.Name == "Nullable`1");
            e.Column.CanUserSort = true;
        }
    }
} 
 


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
GKindel15-Dec-23 3:11
GKindel15-Dec-23 3:11 
GeneralMy vote of 1 Pin
netizenk14-Oct-13 6:33
professionalnetizenk14-Oct-13 6:33 
GeneralRe: ??? Pin
OrlandoCurioso14-Oct-13 6:58
OrlandoCurioso14-Oct-13 6:58 
This is posted as a tip, so please vote on the quality of the tip, and not on the elaborated article you miss.
Try again. Fail again. Fail better. --- Samuel Beckett

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.