2013-02-24 31 views
1

我有一個奇怪的問題,我有一些嵌套循環,我正在從數據網格視圖讀取數據。 如果我在消息框中顯示相同的東西,不會引發異常,當我在字符串中存儲相同的字符時,會出現異常。下面是代碼,幫助從數據網格讀取數據的異常

foreach (DataGridViewRow row in dataGridView1.Rows) 
      { 
      foreach (DataGridViewCell cell in row.Cells) 
      { 
       if (cell.ColumnIndex == 0) //Set your Column Index 
       { 

        String auth = cell.Value.ToString();// here nullexception isthrown 

       } 
+0

顯示消息框中顯示的代碼 – 2013-02-24 08:28:00

+0

MessageBox.Show(cell.Value.ToString()); – mani1989 2013-02-24 08:32:08

+0

您正在使用'String'類,而不是'string'數據類型。我不確定,但這可能是一個問題嗎? – Shaharyar 2013-02-24 08:34:19

回答

1

如果你想避免exception,那麼你應該檢查各行,如果有一些行那麼所有的工作要完成,否則它是無用的。

if(dataGridView1.Rows.Count>0) 
{ 
    foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
     foreach (DataGridViewCell cell in row.Cells) 
     { 
      if (cell.ColumnIndex == 0) //Set your Column Index 
      { 

       string auth = Convert.ToString(cell.Value); 

      } 

使用Convert.ToString(),因爲它也處理null值。

+0

感謝他幫助的人! – mani1989 2013-02-24 08:55:20