0

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?

4

4 回答 4

1

像这样做

             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;
                }
            }
        );
    }
于 2013-07-16T17:17:23.173 回答
0
 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;
                        }
                      }
                    }
                }
            );
        }
于 2013-07-16T17:20:39.347 回答
0

你有一个“产品”列吗?您可以尝试使用索引吗?

r.Cells[1].Value

类似的东西?

此外,您可能必须将其转换为特定的细胞类型?例如:如果它是一个文本框单元格,那么你可能必须这样做

r.Cells[1].Text
于 2013-07-16T17:18:41.320 回答
0

需要检查 cell.Value 是否为空

于 2013-07-17T15:05:29.217 回答