【发布时间】: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);
}
}
【问题讨论】:
-
几乎所有的 NullReferenceException 情况都是一样的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
标签: c# wpf observablecollection radgridview listcollectionview