How to create Cut,Copy,Paste in contextmenu of lisview in Winform c#

Kailash Sahu 141 Reputation points
2021-07-26T23:08:44.767+00:00

I want to create dual context menu in c# , And Click the item I want to add Cut, Copy, Paste

  private void listView1_MouseDown(object sender, MouseEventArgs e)  
 {  
 bool match = false;  

if (e.Button == System.Windows.Forms.MouseButtons.Right)  
{  
    foreach (ListViewItem item in listView1.Items)  
    {  
        if (item.Bounds.Contains(new Point(e.X, e.Y)))  
        {  
            MenuItem[] mi = new MenuItem[] { new MenuItem("Hello"), new MenuItem("World"), new MenuItem(item.Name) };  
            listView1.ContextMenu = new ContextMenu(mi);  
            match = true;  
            break;  
        }  
    }  
    if (match)  
    {  
        listView1.ContextMenu.Show(listView1, new Point(e.X, e.Y));  
    }  
    else  
    {  
        //Show listViews context menu  
    }  

}  

}

117910-mxpex.jpg

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-07-27T05:58:36.713+00:00

    You can first create a contextMenuStrip, add the operations you need, and then use ListView.GetItemAt(Int32, Int32) Method to get the ListViewItem that needs to be operated.

    118165-1.png

            private ListViewItem listViewItem;  
            private void listView1_MouseDown(object sender, MouseEventArgs e)  
            {  
                if (e.Button == MouseButtons.Right)  
                {  
                    if (listView1.GetItemAt(e.X, e.Y) is ListViewItem)  
                    {  
                        contextMenuStrip1.Show(Cursor.Position);  
                        listViewItem = listView1.GetItemAt(e.X, e.Y);  
                    }  
                }  
            }  
            private void removeToolStripMenuItem_Click(object sender, EventArgs e)  
            {  
                listView1.Items.Remove(listViewItem);  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.