How to sort gridview by column containing nullable integer?
Question
I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:
System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.
How do I customize the sorting or comparison logic to handle the null case?
Solution
The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:
gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Only add custom handling for the sort expression on the
// Nullable<int> column
if (e.SortExpression == "MySortExpression")
{
// Convert datasource to a List<T>
list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
{
return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
}));
// Bind the sorted list back to the gridview
}
else
{
// delegate to the gridview to handle its own sorting
}
}
OTHER TIPS
You could also override the null when you bind the data, placing a 0 instead. Your answer is far better. :)
You could also make a custom type that overrides the Compare operator. But that would just duplicate (and complicate) what you have above.