Reputation: 21186
I have the following code:
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if (r.Cells["Product"].Value.ToString() == p.Title)
{
tally += p.Price;
}
}
);
}
At the if statement on run time, I am getting the error
:
An unhandled exception of type 'System.NullReferenceException'
occurred in WindowsFormsApplication1.exe
Additional information: Object reference not set to an instance of an object.
What might be the problem ?
Any thought where i went wrong?
Upvotes: 0
Views: 4361
Reputation: 14470
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if(r.Cells["Product"]!=null)
{
if(r.Cells["Product"].Value!=null)
{
if (r.Cells["Product"].Value.ToString() == p.Title)
{
tally += p.Price;
}
}
}
}
);
}
Upvotes: 0
Reputation: 182
Do you have a column with "Product" exactly? Can you try index instead?
r.Cells[1].Value
something like that?
Also, you might have to convert it into a particular cell type? Ex: if its a textboxcell then you might have to do
r.Cells[1].Text
Upvotes: 0
Reputation: 32729
do it like this
foreach (DataGridViewRow r in DataGridObject.Rows)
{
MyDataSource.ForEach(
delegate( Product p)
{
if (!string.isNullorWhiteSpace(Convert.ToString(r.Cells["Product"].Value)) && Convert.ToString(r.Cells["Product"].Value).Equals(p.Title,StringComparison.OrdinalIgnoreCase))
{
tally += p.Price;
}
}
);
}
Upvotes: 1