Share via


Copy selected listbox items to clipboard

Question

Sunday, March 6, 2011 4:44 AM

I am trying to copy all selected items of a list box to the clipboard. I first am forcing them all to selected. But when I try to copy them all I get is the last in the list.

 private void clipboardbutton_Click(object sender, EventArgs e)
    {
      for(int i = 0; i < ClipboardListBox.Items.Count; i++)
      {
        ClipboardListBox.SetSelected(i, true);
      }
      foreach (Object s in ClipboardListBox.SelectedItems)
      {
        Clipboard.SetText(s.ToString());
      }
    }  

All replies (2)

Sunday, March 6, 2011 5:03 AM ✅Answered

Set the ListBox's SelectionMode to either MultiExtended or MultiSimple. 

Unless this is just test code, you don't even need to select them at all.  You can just iterate through the entire Items collection.

HTH,

ShaneB


Sunday, March 6, 2011 5:05 AM ✅Answered | 2 votes

try the following code to copy value of all the selected items of a listbox

private void clipboardbutton_Click(object sender, EventArgs e)
{
   for(int i = 0; i < ClipboardListBox.Items.Count; i++)
   {
      ClipboardListBox.SetSelected(i, true);
   }
   string s = "";
   foreach(object o in listBox1.SelectedItems)
   {
       s += o.ToString() + "  ";
   }
   Clipboard.SetText(s);
}

How To Articles