Jimmyt1988
Jimmyt1988

Reputation: 21186

iterating over a DataGridView in C# - Object reference not set to an instance of an object

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

Answers (4)

huMpty duMpty
huMpty duMpty

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

delly47
delly47

Reputation: 47

need to check cell.Value for null

Upvotes: 0

seshuk
seshuk

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

Ehsan
Ehsan

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

Related Questions