Daniel Hamutel Daniel Hamutel - 1 month ago 8
C# Question

How can I Copy to clipboard, a ListView's multiple selected items?

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.

Answer

First, you have to enabable multiselect

ListView1.MultiSelect = true;

Then, you can get selected items with

private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
            ListView.SelectedListViewItemCollection selectedItems = 
            istView1.SelectedItems;
            if (e.ClickedItem.Text == "Copy")
            {
                String text = "";
                foreach ( ListViewItem item in selectedItems )
                {
                    text += item.SubItems[1].Text;
                }
                Clipboard.SetText(text);
            }
     }