如何按包含可空整数的列对gridview进行排序?

时间:2020-03-06 15:04:57  来源:igfitidea点击:

我有一个GridView,其中一列绑定到包含可空整数的对象属性。我将SortExpression设置为属性的名称,并且只要所有行都包含一个值,排序就可以完美地进行。但是,如果任何行包含null,我都会得到一个异常:

System.InvalidOperationException:无法比较数组中的两个元素。你调用的对象是空的。

如何自定义排序或者比较逻辑以处理空值情况?

解决方案

Nullable类型公开了用于比较可空类型的比较方法,因此解决方案是覆盖gridview排序逻辑并手动指定比较:

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

绑定数据时,我们也可以覆盖null,而改为0。答案要好得多。 :)

我们还可以创建一个自定义类型,该类型将覆盖Compare运算符。但这只会复制(复杂化)我们上面的内容。