C# gives NullReferenceException while processing lists
The following code gives a NullReferenceException while processing. Can anyone tell me why its happening, and how to fix it? thanks in advance! this might be a very simple thing, I'm missing somewhere.
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);
}
}
}
}
the two lists have been declared at the top of the class so I don't know why its giving this error.
List<DataGridViewRow> a = new List<DataGridViewRow>();
List<DataGridViewRow> b = new List<DataGridViewRow>();
As suggested, I tried using a for loop bit it still gives the same exception
here's the code
if (a.Count != 0)
{
for (int i = a.Coun开发者_Go百科t - 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;
}
}
To find the null pointer exception, use the debugger. One of your variables is null.
But once that is fixed, you cannot modify a list while you are iterating over it. The simplest solution in the code you've presented is to change your foreach
loops into for
loops.
From the MSDN documentation for foreach
:
The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.
You probably have a null
Value
, so ToString()
fails.
A few possibilities:
row.Cells[0]
is nullrow.Cells[1]
is nullrow.Cells[0].Value
is nullrow.Cells[1].Value
is null
You cannot delete an element from a collection that you are iterating through. The solution is to store the list of elements to be deleted in another List, and then delete them in another iteration. Following is a solution.
//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);
}
精彩评论