Cut, Copy, Paste, Select All, Clear All on a ListBox

Have you ever imagined our life without the clipboard ("Cut-Copy-Paste") in today's computer era? Especially a Software Developer's life! These clipboard operations are very common and very frequently used, but here I discuss how to code them (on a ListBox control) instead of just using them.

In this article, I will show some edit operations, like: Select All, Clear All, Cut, Copy and Paste on a ListBox control. To demonstrate this, I created a simple Win form application with a Menu Strip and a ListBox control. On the Menu Strip, all the operations are entered as menu items with short cut keys.

For better understanding, the sample code is also attached with this article. Here is a screenshot of the GUI:

image1.png

Select All

To select all the items in a ListBox, we first clear all the selected items then select each item while iterating through the entire list.

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
     
try
      {
            listBox1.SelectedItems.Clear(); 
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                 listBox1.SetSelected(i, true);
             }
       }
       catch (Exception ex)
       {
             MessageBox.Show(ex.Message);
        }
}

Paste

To paste the text data into our ListBox, we first retrieve the text data from the buffer using the Clipboard class. Since it is a ListBox where each item in the ListBox should correspond to each line in the buffer, here we parse the Text data by a new line character and then store each line as a new item in the ListBox.

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
     
try
      {
           
// Getting Text from Clip board
            string s = Clipboard.GetText(); 
           
//Parsing criteria: New Line
            string[] lines = s.Split('\n'); 
            foreach (string ln in lines)
            {
                 listBox1.Items.Add(ln.Trim());
            }
       }
       catch (Exception ex)
       {
             MessageBox.Show(ex.Message);
        }
}

Copy

To copy the text data into a buffer, we iterate the entire selected item collection and continue to append items into a StringBuilder object. To keep every item in a new row, we are using here AppendLine()method after inserting the item's text into a stringbuilder. Then at the end we use the Clipboard.SetData() method to copy the data into the buffer.

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
     
try
      {
            StringBuilder sb = new StringBuilder(); 
            foreach (object row in listBox1.SelectedItems)
            {
                 sb.Append(row.ToString());
                 sb.AppendLine();
            }
            sb.Remove(sb.Length - 1, 1);
// Just to avoid copying last empty row
            Clipboard.SetData(System.Windows.Forms.DataFormats.Text, sb.ToString());
       }
       catch (Exception ex)
       {
            MessageBox.Show(ex.Message);
       }
}

Cut

Basically a cut operation is the combination of copying and removing the selected items. In order to do this, we start copying all the selected items (as above) into the buffer.

After copying, we remove all the selected items from the ListBox. For this we need another collection to keep all the selected items. We are creating this separate collection because we can't delete items from the collection while iterating the same collection using a foreach loop.

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
    
try
     {
          StringBuilder sb = new StringBuilder();               
         
// we use this collection to keep all the Selected Items
          List<object> selectedItemList = new List<object>();
          foreach (object row in listBox1.SelectedItems)
          {
                sb.Append(row.ToString());
                sb.AppendLine();
                
               
// Keep on adding selected item into a new List of Object
                selectedItemList.Add(row);
           } 
          sb.Remove(sb.Length - 1, 1);   
// Just to avoid copying last empty row                
          Clipboard.SetData(System.Windows.Forms.DataFormats.Text, sb.ToString());
         
// Removing selected items from the ListBox
           foreach (object ln in selectedItemList)
           {
                listBox1.Items.Remove(ln);
            }
     }
     catch (Exception ex)
     {
           MessageBox.Show(ex.Message);
      }
}

Clear All

This is the simplest operation. We need to just clear all the items from the ListBox using the built-in Clear() method.

private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)
{
     listBox1.Items.Clear();
}

Up Next
    Ebook Download
    View all
    Learn
    View all