Search code examples
c#wpfobservablecollectionradgridviewlistcollectionview

Null Reference Exception trying to add blank row to Telerik RadGrid


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

Solution

  • 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());
    }