views:

1391

answers:

3

I have a datagrid 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.

+1  A: 

You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.

Then use a ContextMenu object to display you popup menu, customised for the current row.

Here's a quick and dirty example of what I mean...

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenu m = new ContextMenu();
        m.MenuItems.Add(new MenuItem("Cut"));
        m.MenuItems.Add(new MenuItem("Copy"));
        m.MenuItems.Add(new MenuItem("Paste"));

        int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;

        if (currentMouseOverRow >= 0)
        {
            m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
        }

        m.Show(dataGridView1, new Point(e.X, e.Y));

    }
}

private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    currentMouseOverRow = e.RowIndex;
}

private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    currentMouseOverRow = -1;
}
Stuart Helwig
Correct! and a note for you, var r = dataGridView1.HitTest(e.X, e.Y); r.RowIndex works WAY BETTER then using mouse or currentMouseOverRow
acidzombie24
Right you are. Thanks. Have edited answer to reflect your improvement.
Stuart Helwig
A: 

Simply drag a ContextMenu or ContextMenuStrip component into your form and visually design it, then assign it to the ContextMenu or ContextMenuStrip property of your desired control.

Captain Comic
A: 

The open source project below can abstract all the code required to do this: http://sl4popupmenu.codeplex.com You can use the GetClickedElement function of the menu to identify the clicked row and to avoid selecting items just set its AutoSelectItem property to false.

Ziad