I have a user control in that a grid gets data using ObjectDataSource. All the columns in the grid are sortable. If the user clicks on a particular column name, the list is sorted based on that column (List.Sort(sortColumn)).
I am facing an issue when one of the column has blank / null value in their field. The comparison line strA.CompareTo(strB) fails with "Object reference not set to an instance of an object" when strA/ strB is null or both are null.
How ever, I have included !string.IsNullOrEmpty() for strA and strB to avoid the null refernce exception. Still it doesn't sort the grid.
The code snippet is given below.
int IComparer<MyWorklistItem>.Compare(MyWorkItem x, MyWorkItem y)
{
int sortValue = 1;
if (this.strSortField.Length == 0)
{
return 0;
}
MyWorkItem item1 = this.blnSortDesc ? y : x;
MyWorkItem item2 = this.blnSortDesc ? x : y;
PropertyInfo property1 = item1.GetType().GetProperty(this.strSortField);
PropertyInfo property2 = item2.GetType().GetProperty(this.strSortField);
string strA = (string)property1.GetValue(item1, null);
string strB = (string)property2.GetValue(item2, null);
if (!string.IsNullOrEmpty(strA) && !string.IsNullOrEmpty(strB))
{
sortValue = strA.CompareTo(strB);
}
return sortValue;
}
How do I sort, when one of the values or both are null.
Note: I am using VS 2005, so no possibility for LINQ though.
Please suggest.
Thanks, Sriram
You can use the static string.Compare
method rather than the instance method to avoid problems with null, given that you are always comparing string properties.
http://msdn.microsoft.com/en-us/library/system.string.compare.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With