簡體   English   中英

在C#中遍歷DataGridView-對象引用未設置為對象的實例

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

我有以下代碼:

        foreach (DataGridViewRow r in DataGridObject.Rows)
        {
            MyDataSource.ForEach( 
                delegate( Product p)
                {
                    if (r.Cells["Product"].Value.ToString() == p.Title)
                    {
                        tally += p.Price;
                    }
                }
            );
        }

在運行時的if語句中, error

An unhandled exception of type 'System.NullReferenceException' 
occurred in WindowsFormsApplication1.exe

Additional information: Object reference not set to an instance of an object.

可能是什么問題?

有沒有想到我錯了?

像這樣做

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

您是否有“產品”一欄? 您可以改用索引嗎?

r.Cells[1].Value

這樣的東西?

另外,您可能必須將其轉換為特定的單元格類型? 例如:如果它是一個textboxcell,那么您可能需要做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM