2017-01-16 93 views
0

我有一個DataGridView,包括一個DataGridViewButtonColumn。用戶應該能夠直接使用按鈕,因此我將EditMode設置爲EditOnEnter。但是,第一次點擊並沒有激發Click事件 - 看起來第一次點擊選擇/聚焦行/列?DataGridView中手動觸發按鈕單擊事件

於是,我就用CellClick事件:

Private Sub dgv_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellClick 

Dim validClick = (e.RowIndex <> -1 And e.ColumnIndex <> -1) 
If (TypeOf dgv.Columns(e.ColumnIndex) Is DataGridViewButtonColumn And validClick) Then 
    dgv.BeginEdit(True) 
    CType(dgv.EditingControl, Button).PerformClick() 
End If 

End Sub 

但這種方法也不能工作。 EditingControl總是拋出一個NullReferenceException

任何想法?

+1

看一看答案[這裏](http://stackoverflow.com/questions/3577297/how-to-handle-click-event-in-button-column-in-datagridview)。這是一個C#的問題,但答案轉換爲VB.NET,所以你應該能夠從中挑選出一些位。 – Bugs

+0

謝謝,我看到了這個問題。問題不在於運行任何函數/方法/事件 - 問題是,即使DataGridView EditMode是EditOnEnter **,**第一次單擊始終關注該行並且不會觸發CellClick/CellContentClick事件。有什麼解決方法嗎?每當用戶點擊一個DataGridViewButtonColumn時,DataGridViewButtonColumn背後的代碼應該會觸發...... – tmieruch

回答

1

我不認爲當點擊一個DataGridViewButtonColumn單元時,有一個特定的事件可以處理。 DataGridViewCell_ClickedCellContentClicked事件被解僱。

我無法獲得點擊進入DataGridView的延遲,然後再次點擊以啓動按鈕。當我點擊DataGridView按鈕單元時,立即啓動了Cell_Clicked事件。更改DataGridViewEditMode沒有什麼區別。下面的代碼簡單地標識了從Cell_Clicked事件中點擊了WHICH單元。如果單擊的單元格是按鈕列(1或2),則我調用創建的方法ButtonHandler來處理按下哪個按鈕並繼續按正確的按鈕方法。希望這可以幫助。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { 
    if (e.ColumnIndex == 1 || e.ColumnIndex == 2) { 
    // one of the button columns was clicked 
    ButtonHandler(sender, e); 
    } 
} 

private void ButtonHandler(object sender, DataGridViewCellEventArgs e) { 
    if (e.ColumnIndex == 1) { 
    MessageBox.Show("Column 1 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked"); 
    // call method to handle column 1 button clicked 
    // MethodToHandleCol1ButtonClicked(e.RowIndex); 
    } 
    else { 
    MessageBox.Show("Column 2 button clicked at row: " + e.RowIndex + " Col: " + e.ColumnIndex + " clicked"); 
    // call method to handle column 2 button clicked 
    // MethodToHandleCol2ButtonClicked(e.RowIndex); 
    } 
} 
相關問題