简体   繁体   中英

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?

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;
                }
            }
        );
    }

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
 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;
                        }
                      }
                    }
                }
            );
        }

需要检查cell.Value是否为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM