2013-05-26 22 views
0

我在用戶控件上有一個datagrid,其中「修飾符」是公開的。我有以下代碼:「未設置爲一個對象的實例對象引用」獲取datagridview的值時出錯

for (int f = 0; f < gridOperations.Rows.Count; f++) 
{ 
    for (int z = 0; f < gridOperations.Rows[f].Cells.Count; z++) 
    { 
      MessageBox.Show(gridOperations.Rows[f].Cells[z].Value.ToString()); 
    } 
} 

的問題是,如果Z變得大於0它給了我

我不明白爲什麼會這樣,如果我這樣做:

MessageBox.Show(gridOperations.Rows[0].Cells.Count.ToString()); 

它顯示了9個項目,所以有細胞,我只是不明白爲什麼它不會讓我訪問它們。謝謝!

+0

你測試我的回答?有什麼例外? – Damith

+0

@Damith我測試過,我仍然得到相同的例外,怪異..任何其他想法?謝謝 – Kristian

+0

如何綁定datagridview?你想要哪個列獲得價值? – Damith

回答

0

試試下面

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    foreach (DataGridViewCell cell in row.Cells) 
    { 
     if (cell.Value !=null) 
     { 
      MessageBox.Show(cell.Value.ToString()); 
     } 
    } 
} 
+0

謝謝,但我得到同樣的例外 – Kristian

+0

@Kristian加了空檢查,請檢查 – Damith

0

試圖改變這樣的..

for (int f = 0; f < gridOperations.Rows.Count-1; f++) 
{ 
    for (int z = 0; f < gridOperations.ColumnCount -1; z++) 
    { 
      MessageBox.Show(gridOperations.Rows(f).Cells(z).Value.ToString()); 
    } 
} 
+0

謝謝!它說GridOperations不包含'Cells'的定義謝謝 – Kristian

+0

@Kristian:回答編輯... – matzone

+0

謝謝,但我仍然得到例外。數據網格使用數據源,這可能是一個問題? – Kristian

0

試試這個;

for (int f = 0; f < gridOperations.Rows.Count; f++) 
{ 
    for (int z = 0; z < gridOperations.Rows[f].Cells.Count; z++) 
    { 
      MessageBox.Show(gridOperations.Rows[f].Cells[z].Value.ToString()); 
    } 
} 

我認爲真正的問題是在這裏,你有界的內部for循環與f < gridOperations.Rows[f].Cells.Count whihc我想應該是z < gridOperations.Rows[f].Cells.Count,因爲您的綁定爲循環應該是當前行的細胞計數,沒有的數量當前行。

作爲替代方案,因爲DataGridViewRowCollectionDataGridViewCellCollection實現IEnumerable接口,可以使用foreach環等;

foreach (DataGridViewRow rows in gridOperations.Rows) 
{        
    foreach (DataGridViewCell cells in rows.Cells) 
    { 
     MessageBox.Show(cells.Value.ToString()); 
    } 
} 
+0

謝謝。發生同樣的nullReferenceException,第二個示例不編譯(Object不包含'Cells') – Kristian

+0

@Kristian更新了第二個示例。你可以檢查它。 –

+0

謝謝,但我仍然得到空例外。它只在cellID爲0時有效,當它爲1時,我得到異常。 – Kristian