right click context menu for datagridview

Viewed 271275

I have a datagridview in a .NET winform app. I would like to rightclick on a row and have a menu pop up. Then i would like to select things such as copy, validate, etc

How do i make A) a menu pop up B) find which row was right clicked. I know i could use selectedIndex but i should be able to right click without changing what is selected? right now i could use selected index but if there is a way to get the data without changing what is selected then that would be useful.

8 Answers
  • Put a context menu on your form, name it, set captions etc. using the built-in editor
  • Link it to your grid using the grid property ContextMenuStrip
  • For your grid, create an event to handle CellContextMenuStripNeeded
  • The Event Args e has useful properties e.ColumnIndex, e.RowIndex.

I believe that e.RowIndex is what you are asking for.

Suggestion: when user causes your event CellContextMenuStripNeeded to fire, use e.RowIndex to get data from your grid, such as the ID. Store the ID as the menu event's tag item.

Now, when user actually clicks your menu item, use the Sender property to fetch the tag. Use the tag, containing your ID, to perform the action you need.

There is simple answer to this topic and that is to use CellMouseDown

  1. After designing your ContextMenu
// somewhere in your code

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add(new MenuItem("Option1"));
cm.MenuItems.Add(new MenuItem("Option2"));
  1. Assign it to the DataGridView
myDataView.ContextMenu = cm;
  1. Get Data from the CLICKED cell without changing the Selected one
private void myDataView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
         string myData = myDataView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

         // Now ADD the captured DATA to the ContextMenu
         cm.MenuItems.Add(new MenuItem("myData"));

         // OR if you are doing it by the designer and YOU ALREADY have an Item
         // you can simply change the name of it in the designer page to your
         // desired one and then just change the Text of it
         MenuItem_BTN.Text = "$Properties of {myData}";
    }
}
Related