使用Linq迭代DataGridView子集时的对象引用错误

时间:2015-03-09 23:42:23

标签: c# linq datagridview ado.net linq-to-dataset

编辑:我理解NRE的基础知识,我不明白这个LINQ查询和我的datagridview发生的确切原因。我看到必须注意“新行”,但我尝试了三种不同的调整方式 - 在两种情况下使用IsNewRow并尝试以where grid.Index != dgv_Exhibitors.NewRowIndex作为第三种情况。请帮助我理解为什么会发生这种情况以及如何纠正它,而不是仅仅将其视为副本。

我有代码将DataGridView中的列与DataTable中的列进行比较。目的是查找并突出显示DataTable中不存在的单元格。但是,在更改单元格颜色后,我收到了对象引用错误。

private void ValidateData()
{
    DataTable dtSubs = Controller.Instance.GetSubaccounts();

    var entriesNotInSubs =
        dt.AsEnumerable().Select(r => r.Field<string>("EXHIBITOR").Trim()).Except(dtSubs.AsEnumerable().Select(r => r.Field<string>("SGMNTID").Trim()));

    var invalidExhibitors =
        from grid in dgv_Exhibitors.Rows.OfType<DataGridViewRow>()
        join segment in entriesNotInSubs on grid.Cells["EXHIBITOR"].Value.ToString().Trim() equals segment.Trim()
        select grid;

    foreach (var row in invalidExhibitors)
    {
        row.Cells["EXHIBITOR"].Style.BackColor = Color.Red;
    }
}

我不太确定如何解释错误信息,除了在MoveNext()上发生错误,但哪一行是问题?谢谢你的时间。

System.NullReferenceException: Object reference not set to an instance of an object. 
at VirtualPrintFeesGPAddin.ExhibitorMaint.<ValidateData>b__6(DataGridViewRow grid) 
at System.Linq.Enumerable.<JoinIterator>d__61`4.MoveNext()    
at VirtualPrintFeesGPAddin.ExhibitorMaint.ValidateData() 
at VirtualPrintFeesGPAddin.ExhibitorMaint.btnValidate_Click(Object sender, EventArgs e)

更新:我已经完成了以下操作,并且在没有检查IsNewRow属性的情况下得到完全相同的错误。

foreach (var row in invalidExhibitors)
{
    if (row.IsNewRow == false)
        row.Cells["EXHIBITOR"].Style.BackColor = Color.Red;
}

更新2:我也对其进行了测试:

from grid in dgv_Exhibitors.Rows.OfType<DataGridViewRow>()
join segment in entriesNotInSubs on grid.Cells["EXHIBITOR"].Value.ToString().Trim() equals segment.Trim()
where grid.IsNewRow == false 
select grid;

它提供了稍微不同的错误信息:

at System.Linq.Enumerable.<JoinIterator>d__61`4.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()

1 个答案:

答案 0 :(得分:0)

经过多次重写之后,我找到了一个解决方案,我认为这个解决方案会像其他所有人一样失败,但令我惊讶的是使用了两个Where子句最终起作用。

var entriesNotInSubs =
    dt.AsEnumerable().Select(r => r.Field<string>("EXHIBITOR").Trim()).Except(dtSubs.AsEnumerable().Select(r => r.Field<string>("SGMNTID").Trim()));

var dgvRow_ExhibitorNotInSubs =
    (from exibitors in dgv_Exhibitors.Rows.OfType<DataGridViewRow>()
    select exibitors)
        .Where(j => j.IsNewRow == false)
        .Where(i => entriesNotInSubs.Contains(i.Cells[0].Value.ToString().Trim()));

foreach (var row in dgvRow_ExhibitorNotInSubs)
{
    row.Cells[0].Style.BackColor = Color.OrangeRed;
}