How to copy selected item in list box in C#?
13,505
Solution 1
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);
}
}
Solution 2
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>() ) );
Solution 3
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
Author by
J .A
Updated on June 05, 2022Comments
-
J .A almost 2 years
How to copy selected item in list box to clipboard, using right click "Copy" menu?
-
Jim Simson almost 6 years+1 because of the completeness of the answer, but I would add that you need to check for a null selection otherwise it will throw an error if nothing is selected ( && listBox1.SelectedItems.Count > 0).