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.
First, you have to enable multiselect:
ListView1.MultiSelect = true;
Then, you can get selected items with:
private void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ListView.SelectedListViewItemCollection selectedItems =
ListView1.SelectedItems;
if (e.ClickedItem.Text == "Copy")
{
String text = "";
foreach ( ListViewItem item in selectedItems )
{
text += item.SubItems[1].Text;
}
Clipboard.SetText(text);
}
}
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
CopyListBox(listBox1);
}
}
public void CopyListBox(ListBox list)
{
StringBuilder sb = new StringBuilder();
foreach (string item in list.SelectedItems)
{
sb.AppendLine(item);
}
Clipboard.SetDataObject(sb.ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With