0

Can someone please tell me why I keep getting a NULL reference exception when trying to perform the add below? This only happens when the ObservableCollection is empty at the beginning. If there is data in the collection from the start it works fine.

Load ObservableCollection and set collection ViewSource:

private void LoadCodeSets()
{
    this.codeSetData = new ObservableCollection<CodeSet>();

    var query = from c in context.CodeSets
                where c.LogicallyDeleted == 0
                orderby c.CodeSetID ascending
                select c;

    foreach (CodeSet c in query)
    {
        this.codeSetData.Add(c);
        this.codeSetView = (ListCollectionView)CollectionViewSource.GetDefaultView(codeSetData);
        this.codeSetRadGridView.ItemsSource = this.codeSetView;
    }
}

Add New Record to Empty Data Grid

private void Add_CodeSet_Click(object sender, RoutedEventArgs e)
{
    try
    {
        bool doesCodeSetExist = false;

        if (codeSetView == null)
        {

            codeSetView.AddNewItem(new CodeSet());
        }
        else
        {
            foreach (CodeSet cs in codeSetView)
            {
                if (cs.CodeSetID == 0)
                {
                    doesCodeSetExist = true;
                    this.lblMessages.Foreground = Brushes.Red;
                    this.lblMessages.FontWeight = System.Windows.FontWeights.ExtraBold;
                    this.lblMessages.Content = "Please fill in new user form and click Save User.";
                    this.lblMessages.Visibility = Visibility.Visible;
                }
            }
            if (!doesCodeSetExist)
            {
                CodeSet newCodeSet = new CodeSet();
                codeSetView.AddNewItem(newCodeSet);
            }
        }
    }
    catch (Exception ex)
    {
        Error.LogError(ex);
    }
}
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
user1599271
  • 69
  • 1
  • 8
  • Almost all cases of NullReferenceException are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jan 15 '13 at 02:19

1 Answers1

1

It looks like this block of code is causing the issue

if (codeSetView == null)
{
    codeSetView.AddNewItem(new CodeSet());
}

If codeSetView is null you cant use codeSetView.AddNewItem. You will have to initiate codeSetView before adding items.

eg:

if (codeSetView == null)
{
    codeSetView = new ...... or (ListCollectionView)CollectionViewSource.GetDefaultView(codeSetData);
    codeSetView.AddNewItem(new CodeSet());
}
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • This is true. I need to figure out how I can default this somehow to init my collection and collection view source. In the case where my linq query does not return any records. – user1599271 Jan 15 '13 at 03:47