簡體   English   中英

如何在DataGridView上使用右鍵單擊上下文菜單?

[英]How can I use a right click context menu on a DataGridView?

我已經創建了一個上下文菜單,並與我的DataGridView控件相關聯。 但是,我注意到當我右鍵單擊控件時,dataGridView中的選擇不會更改。 所以我無法正確獲取上下文的事件處理程序中的行。

有關如何實現這一目標的任何建議?

想象一下,我有一個ID olumn,當​​我點擊刪除上下文菜單時,我想從數據庫中刪除該特定條目。

我只需要有關如何獲取該ID的信息 ,我可以自己處理刪除。

    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);
    }

這是您可以顯示上下文菜單並在單擊單元格時選擇當前單元格的方法。

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);
        }
    }
}

在菜單項的Click事件處理程序中,檢查dataGridView1.CurrentRow以找出當前選擇的行。 例如,如果網格綁定到數據源:

private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    var item = dataGridView1.CurrentRow.DataBoundItem;
}

測試此代碼時,請確保未設置DataGridView.ContextMenuStrip屬性。

加,

DataGridViewRow currentRow;
void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.RowIndex >= 0)
        currentRow = self.Rows[e.RowIndex];
    else
        currentRow = null;
}

然后在上下文菜單方法中使用currentRow。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM