2012-07-23 37 views
1

我正在處理datagrid和cellClick事件,並在相關的texbox上獲取數據以進行編輯。 當我點擊行時,它工作正常,但當我點擊任何列時,它會給出例外,我不知道爲什麼。異常點擊網格列

這裏是我的代碼:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    itmId.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); 
    itmNme.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); 
    untCst.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); 
    qntty.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); 
    manfDate.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(); 
} 
+0

泰德斯賓斯的答案似乎幫助你解決了你的問題。它是解決方案,然後您可以通過單擊答案旁邊的箭頭將其標記爲接受的答案。 – 2012-07-23 21:57:09

回答

4

當你點擊表格的標題,它發出的-1行索引。還有其他的情況下,這個事件可以用無效的rowindex和columnindex值觸發。

在使用它們之前,您應該測試rowindex和columnindex。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { 
     // .. my code goes here .. 
    } 
} 

在某些情況下,你可能還需要測試是否rowIndex位置和columnindex超越備份數據的限制。

+0

我不熟悉dataGrid對象。但通常0是一個有效的索引。 – jsmith 2012-07-23 17:01:18

+0

好的,謝謝! – 2012-07-23 17:12:26

+0

謝謝你,先生,這個問題不再再次感謝 – 2012-07-23 17:57:09