我有一个 GridView,其中一列绑定到一个包含可为空整数的对象属性。我将 SortExpression 设置为属性的名称,只要所有行都包含一个值,排序就可以完美地工作。但是,如果任何行包含 null,我会得到一个异常:
System.InvalidOperationException :无法比较数组中的两个元素。你调用的对象是空的。
如何自定义排序或比较逻辑以处理 null 情况?
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。你的答案要好得多。:)
您还可以创建一个覆盖比较运算符的自定义类型。但这只会重复(并复杂化)您上面的内容。