c# – Calling the menu on pressing the right button in WinForms

Question:

There is some DataGridView.

It is necessary when you click on the right button to display a context menu with actions on this cell.

Tell me how it's done?

Answer:

Attaching a context menu to the DataGridView .

Subscribe to the ContextMenuStrip.Opening event:

private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
    var point = dataGridView.PointToClient(contextMenuStrip.Bounds.Location);
    var info = dataGridView.HitTest(point.X, point.Y);

    // Отменяем показ контекстного меню, если клик был не на ячейке
    if (info.RowIndex == -1 || info.ColumnIndex == -1)
    {
        e.Cancel = true;
    }
}

In the click handler of the necessary context menu items related to cells, we write:

private void ToolStripItem_Click(object sender, System.EventArgs e)
{
    var point = dataGridView.PointToClient(contextMenuStrip.Bounds.Location);
    var info = dataGridView.HitTest(point.X, point.Y);

    // Работаем с ячейкой
    var value = dataGridView[info.ColumnIndex, info.RowIndex].Value;
}

Another variant.

We show the context menu manually when it is needed. To do this, we subscribe to the DataGridView.CellContextMenuStripNeeded event:

private void DataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    if (e.ColumnIndex != -1 && e.RowIndex != -1)
    {
        contextMenuStrip.Show(Cursor.Position);
    }
}

There is no need to attach the menu to the DataGridView itself. And remove the handling of the ContextMenuStrip.Opening event.
The ToolStripItem.Click event handlers remain unchanged.

Scroll to Top