2012-06-25 56 views
0

我無法讓我的應用程序正常工作。我想用鼠標在datagridview中選擇一行。我需要保存該行的索引以允許我導航選定的行。檢測鼠標點擊在dataGridView中選擇一行

我一直在看DataGridView.CellMouseClick事件(Link)但我無法確保事件處理程序與CellMouseClick事件關聯。

我給這家到目前爲止的代碼很簡單,我只是想看看它的檢測鼠標點擊:

public event DataGridViewCellMouseEventHandler CellMouseClick; 

    private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e) 
    { 
     MessageBox.Show("Mouse clicked in the datagridview!"); 
    } 

誰能指出哪裏我可能會錯誤。任何幫助將是偉大的!

回答

5

您需要「wireup」這個事件。

如果您的DataGridView被稱爲DataGridView1那麼你需要下面的無論是在構造函數中的表單代碼行,設計師(如果您添加通過設計師的事件處理程序)或Load事件:

DataGridView1.CellMouseClick += DataGridView1_CellMouseClick; 

這會將代碼中的事件處理程序附加到事件中。

您當前的樣品看起來像這樣:

public event DataGridViewCellMouseEventHandler CellMouseClick; 

    private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e) 
    { 
     MessageBox.Show("Mouse clicked in the datagridview!"); 
    } 

沒有必要重新聲明,除非你正在構建自己的用戶控件,將舉辦一個DataGridView,你想有效事件to "wrap" or "rebroadcast" that事件(public event DataGridViewCellMouseEventHandler CellMouseClick;)。

+0

啊,我知道我確實需要以某種方式連線它。感謝您的詳細解釋和有用的鏈接。優秀的答案! – L337BEAN