Daniel Lip
Daniel Lip

Reputation: 11319

Why the ContextMenu right mouse click on ListView items is not working?

At the top of form1:

private ContextMenuStrip contextmenustrip1 = new ContextMenuStrip();

Then:

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        ListView listView = sender as ListView;
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            ListViewItem item = listView.GetItemAt(e.X, e.Y);
            if (item != null)
            {
                item.Selected = true;
                contextmenustrip1.Show(listView, e.Location);
            }
        }
        ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
        MenuItem menuItem = new MenuItem("Cut");
        menuItem.Click += new EventHandler(CutAction);
        contextMenu.MenuItems.Add(menuItem);
        menuItem = new MenuItem("Copy");
        menuItem.Click += new EventHandler(CopyAction);
        contextMenu.MenuItems.Add(menuItem);
        menuItem = new MenuItem("Paste");
        menuItem.Click += new EventHandler(PasteAction);
        contextMenu.MenuItems.Add(menuItem);
    }
}

When i make click on item using a break point it's getting to the event but the right mouse click is not working but for sure it's not showing the menus the Cut Copy Paste.

I want to make that when i make right click on item in the listView it will show the menu for the current item. Not sure if i should first make mousedown first or some other event not sure what's more logic. But the idea is to show the menu per right mouse click on item.

Upvotes: 1

Views: 6981

Answers (1)

Raktim Biswas
Raktim Biswas

Reputation: 4077

You don't need to do anything of the above. Simply, call the Click event of the menu item.

Firstly, set the View Mode of your ListView to Details and then set the ContextMenuStrip Property of the ListView to contextMenuStrip1.

ContextMenuStrip:

The shortcut menu to display when the user right clicks the control.

So, say for Cut menu, call the Click event CutToolStripMenuItem. Similarly, call the events for Copy and Paste as well and add your code.

private void CutToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count != 0)
    {
        foreach (ListViewItem LItem in listView1.SelectedItems)
        {
            //Your code                  
        }
    }
}

                                           right_click

Upvotes: 1

Related Questions