This is a Microsoft example:
DataGridViewRow.ContextMenuStrip Property (System.Windows.Forms) | Microsoft Learn[
^]
Create a new project, drop a
DataGridView
control on a form, then add the following code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitData();
}
public List<Person> People { get; set; } = new List<Person>
{
new Person { Age = 21, FirstName = "Paul", LastName = "McCartney" },
new Person { Age = 22, FirstName = "John", LastName = "Lennon" },
new Person { Age = 23, FirstName = "George", LastName = "Harrison" },
new Person { Age = 24, FirstName = "Ringo", LastName = "Starr" },
};
private void InitData()
{
dataGridView1.MultiSelect = false;
dataGridView1.DataSource = People;
dataGridView1.Rows[0].Cells[0].Selected = true;
AddContextMenu();
dataGridView1.CellMouseEnter += dataGridView_CellMouseEnter;
}
ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem();
private void AddContextMenu()
{
toolStripItem1.Text = "Redden";
toolStripItem1.Click += new EventHandler(toolStripItem1_Click);
ContextMenuStrip strip = new ContextMenuStrip();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
column.ContextMenuStrip = strip;
column.ContextMenuStrip.Items.Add(toolStripItem1);
}
}
private DataGridViewCellEventArgs mouseLocation;
private void toolStripItem1_Click(object sender, EventArgs args)
{
dataGridView1.Rows[mouseLocation.RowIndex]
.Cells[mouseLocation.ColumnIndex].Style.BackColor
= Color.Red;
}
private void dataGridView_CellMouseEnter(object sender,
DataGridViewCellEventArgs location)
{
mouseLocation = location;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Now run and right-click on any cell. A context menu is shown and you can select the item and the click event is captured.