Null Reference Exception in SortedBindingList

Null Reference Exception in SortedBindingList

Old forum URL: forums.lhotka.net/forums/t/1811.aspx


cds posted on Tuesday, November 21, 2006

Hi

I'm using nullable types extensively in my BOs and when I use a SortedBindingList on a property that can be null, it blows up on the null value. I can fix it by changing the CompareTo method as follows (bolded lines are added code)

public int CompareTo(ListItem other)
{
object target = other.Key;

if (Key is IComparable)
  return ((IComparable)Key).CompareTo(target);

else
{
    if (Key == null)
        return 0;
   
  if (Key.Equals(target))
    return 0;
  else
    return Key.ToString().CompareTo(target.ToString());
}
}

Thanks for an awesome framework!

Craig

 

RockfordLhotka replied on Tuesday, November 21, 2006

Thanks for letting me know, I've made the change in the code in cvs, so it will be in the next release.

KGy replied on Tuesday, April 05, 2011

ListItem.CompareTo still may throw exceptions when the original list contains null elements (in 3.8.4). Occurs when only other.Key is null (this.Key is not null).

Correction is bold:

public int CompareTo(ListItem other)
{
    object target = other.Key;

    if (Key is IComparable)
        return ((IComparable)Key).CompareTo(target);

    else
    {
        if (Key == null)
        {
            if (target == null)
                return 0;
            else
                return 1;
        }
        else if (Key.Equals(target))
            return 0;

        else if (target == null)
            return 1;

        return Key.ToString().CompareTo(target.ToString());
    }
}

RockfordLhotka replied on Tuesday, April 05, 2011

Added to bug list, thanks.

Copyright (c) Marimer LLC