【问题标题】:Null Reference Exception trying to add blank row to Telerik RadGrid [closed]尝试将空白行添加到 Telerik RadGrid 的空引用异常 [关闭]
【发布时间】:2013-01-15 02:06:29
【问题描述】:

有人能告诉我为什么我在尝试执行下面的添加时总是收到 NULL 引用异常吗?这只发生在ObservableCollection 开头为空时。如果集合中从一开始就有数据,它就可以正常工作。

加载ObservableCollection并设置集合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;
    }
}

向空数据网格添加新记录

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

【问题讨论】:

标签: c# wpf observablecollection radgridview listcollectionview


【解决方案1】:

看起来是这段代码导致了问题

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

如果codeSetViewnull,则不能使用codeSetView.AddNewItem。 在添加项目之前,您必须启动 codeSetView

例如:

if (codeSetView == null)
{
    codeSetView = new ...... or (ListCollectionView)CollectionViewSource.GetDefaultView(codeSetData);
    codeSetView.AddNewItem(new CodeSet());
}

【讨论】:

  • 这是真的。我需要弄清楚如何以某种方式默认它来初始化我的集合和集合视图源。在我的 linq 查询不返回任何记录的情况下。
猜你喜欢
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多