<p>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:</p>

<p>System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.</p>

<p>How do I customize the sorting or comparison logic to handle the null case?</p>

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
    }
}
```
```