问题描述
|
以下代码在处理时给出了NullReferenceException。谁能告诉我为什么会这样,以及如何解决?提前致谢!这可能是一件非常简单的事情,我在某个地方不见了。
if (a.Count != 0)
{
foreach(DataGridViewRow row in a )
{
foreach (DataGridViewRow newrow in b)
{
if( row.Cells[0].Value.ToString() == newrow.Cells[0].Value.ToString() &&
row.Cells[1].Value.ToString() == newrow.Cells[1].Value.ToString()) // this is the line that gives the error.
{
a.Remove(row);
}
}
}
}
这两个列表已在类的顶部声明,因此我不知道为什么会出现此错误。
List<DataGridViewRow> a = new List<DataGridViewRow>();
List<DataGridViewRow> b = new List<DataGridViewRow>();
正如建议的那样,我尝试使用for循环位,但仍然给出相同的异常
这是代码
if (a.Count != 0)
{
for (int i = a.Count - 1; i >= 0; i--)
{
int index1 = i;
for (int k = 0; k < b.Count; k++)
{
int index2 = k;
if (a.ElementAt<DataGridViewRow> (index1).Cells[0].Value.ToString() == b.ElementAt<DataGridViewRow>(index2).Cells[0].Value.ToString() && a.ElementAt<DataGridViewRow>(index1).Cells[1].Value.ToString() == b.ElementAt<DataGridViewRow>(index2).Cells[1].Value.ToString())
{
a.RemoveAt(index1);
}
else continue;
}
}
解决方法
要查找空指针异常,请使用调试器。您的变量之一为null。
但是,一旦修复该问题,就无法在迭代列表时修改列表。您提供的代码中最简单的解决方案是将
foreach
循环更改为for
循环。
从foreach
的MSDN文档中:
foreach语句为数组或对象集合中的每个元素重复一组嵌入式语句。 foreach语句用于遍历集合以获取所需的信息,但不应用于更改集合的内容,以避免不可预期的副作用。
, 您可能有null
Value
,因此ToString()
失败了。
, 一些可能性:
row.Cells[0]
为空
row.Cells[1]
为空
row.Cells[0].Value
为空
row.Cells[1].Value
为空
, 您不能从要迭代的集合中删除元素。解决方案是将要删除的元素列表存储在另一个List中,然后在另一个迭代中将其删除。以下是一个解决方案。
//New list that will contain the Objects to be deleted later on.
List<DataGridView> listToDelete = new List<DataGridView>();
if (a.Count != 0)
{
foreach(DataGridViewRow row in a )
{
foreach (DataGridViewRow newrow in b)
{
if( row.Cells[0].Value.ToString() == newrow.Cells[0].Value.ToString() &&
row.Cells[1].Value.ToString() == newrow.Cells[1].Value.ToString())
{
listToDelete.Add(row);
}
}
}
}
foreach (DataGridView d in listToDelete) {
a.Remove(d);
}