This code is working for one single selected item:
In the top:
ContextMenuStrip menuStrip;
Then in the constructor:
menuStrip = new ContextMenuStrip();
menuStrip.ItemClicked += menuStrip_ItemClicked;
menuStrip.Items.Add("Cut");
menuStrip.Items.Add("Copy");
menuStrip.Items.Add("Paste");
The menuStrip
itemclicked event:
ListViewItem item;
private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Copy")
{
Clipboard.SetText(item.SubItems[1].Text);
}
}
Then the ListView
mouse click event:
private void lstDisplayHardware_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
item = lstDisplayHardware.GetItemAt(e.X, e.Y);
menuStrip.Show(lstDisplayHardware, e.Location);
}
}
This code is working for single selected item.
For example I click on an item in the ListView
, right click on the item and select Copy
: the selected item's subitem is copied to the Clipboard.
But now I want to do the same thing for multiple selection.
So if I use Ctrl+Left mouse click and for example selected 4 items and invoke Copy
command from the context menu, I expect all subitems of the 4 selected items text to be copied into the Clipboard.
For example I have these items:
danny hello world
daniel hi all
dan rain today
daniels sunny day
I select the items:
danny
daniel
dan
daniels
Then right click and click on Copy.
When I paste
anywhere from the clipboard I want it to show:
hello world
hi all
rain today
sunny day
All of the sub items of the selected items in the same order and format.
Best Answer
First, you have to enable multiselect:
Then, you can get selected items with: