我創建了一個上下文菜單,並關聯到我的DataGridView控件。但是,我注意到,當我右鍵單擊該控件時,dataGridView中的選擇內容不會更改。所以我無法正確地獲取上下文的事件處理程序中的行。如何在DataGridView上使用右鍵單擊上下文菜單?
有關如何完成此任務的任何建議?
想象一下,我有一個ID olumn,當我單擊刪除上下文菜單時,我想從數據庫中刪除該特定條目。
我只需要關於的信息如何獲得那個ID,我可以處理刪除自己。
我創建了一個上下文菜單,並關聯到我的DataGridView控件。但是,我注意到,當我右鍵單擊該控件時,dataGridView中的選擇內容不會更改。所以我無法正確地獲取上下文的事件處理程序中的行。如何在DataGridView上使用右鍵單擊上下文菜單?
有關如何完成此任務的任何建議?
想象一下,我有一個ID olumn,當我單擊刪除上下文菜單時,我想從數據庫中刪除該特定條目。
我只需要關於的信息如何獲得那個ID,我可以處理刪除自己。
添加,
DataGridViewRow currentRow;
void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
currentRow = self.Rows[e.RowIndex];
else
currentRow = null;
}
然後在上下文菜單的方法使用currentRow。
這是如何顯示上下文菜單並選擇當前單元格,如果單元格被點擊。
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
if (hit.Type == DataGridViewHitTestType.Cell)
{
dataGridView1.CurrentCell = dataGridView1[hit.ColumnIndex, hit.RowIndex];
contextMenuStrip1.Show(dataGridView1, e.X, e.Y);
}
}
}
從您的菜單項中點擊事件處理程序檢查dataGridView1.CurrentRow以找出當前選中的行。例如,如果網格綁定到數據源:
private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
var item = dataGridView1.CurrentRow.DataBoundItem;
}
當你測試此代碼,請確保DataGridView.ContextMenuStrip屬性未設置。
這工作很好。謝謝。 – shindigo 2011-06-24 15:35:34
@shindigo - 對不起,我很困惑,我沒有注意到,這不是你的問題首先:)。 – 2011-06-29 18:04:59
private void dataGridViewSource_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button != MouseButtons.Right || e.RowIndex == -1 || e.ColumnIndex == -1) return;
dataGridViewSource.CurrentCell = dataGridViewSource.Rows[e.RowIndex].Cells[e.ColumnIndex];
contextMenuStripGrid.Show(Cursor.Position);
}
因此,CellMouse_Down在右擊時被觸發? – 2011-05-22 03:04:52
如果您將CellMouseDown處理程序添加到網格,它將會生效。 – 2011-05-22 05:36:49