Reputation: 63
How to copy selected item in list box to clipboard, using right click "Copy" menu?
Upvotes: 3
Views: 19402
Reputation: 331
I clicked on my listbox to create an automatic function inside the form class.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Clipboard.SetDataObject(this.listBox1.SelectedItem.ToString());
}
I added the Clipboard.SetDataObject() line and it works.
Upvotes: 0
Reputation: 853
To copy all the items in the listbox to the clipboard:
Clipboard.SetText( string.Join( Environment.NewLine, ListBox1.Items.OfType<string>() ) );
To copy just the selected lines in the listBox to the clipboard (listbox SelectionMode is MultiExtended):
Clipboard.SetText( string.Join( Environment.NewLine, ListBox1.SelectedItems.OfType<string>() ) );
Upvotes: 7
Reputation: 439
If you want to select an item, and do ctrl + c then use this code:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.C)
{
string s = listBox1.SelectedItem.ToString();
Clipboard.SetData(DataFormats.StringFormat, s);
}
}
Upvotes: 10
Reputation: 661
To manipulate text in the clipboard, you can use the static Clipboard class:
Clipboard.SetText("some text");
http://msdn.microsoft.com/en-us/library/system.windows.clipboard(v=vs.110).aspx
Upvotes: 2