break

C#: Right click in a dataGridView cell

I have a contextMenuStrip with 2 items. I have several columns in my datagridview, and I wanted to display one menu when the user right clicks on a specific column (named Allocated), and display the other menu when the user right clicks on any other column.

There’s not an event in a datagridview for a right click, but to do this you can use the CellMouseDown event, and find out there if the user did a right click.

Here’s a solution to this problem:
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
string column = dataGridView.Columns[e.ColumnIndex].Name;
if (column == "Allocated")
{
contextMenuStrip1.Items[0].Visible = false;
contextMenuStrip1.Items[1].Visible = true;
}
else
{
contextMenuStrip1.Items[0].Visible = true;
contextMenuStrip1.Items[1].Visible = false;
}
}
}

Basically in this line : if (e.Button == MouseButtons.Right)
You find out, if the user did a right click with their mouse.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image