Export (0) Print
Expand All

How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control

Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources. However, this topic demonstrates the simplest method and requires no data binding. The items displayed are usually strings; however, any object can be used. The text that is displayed in the control is the value returned by the object'sToString method.

To add items

  1. Add the string or object to the list by using the Add method of the ObjectCollection class. The collection is referenced using theItems property:

    comboBox1.Items.Add("Tokyo");
    

    - or -

  2. Insert the string or object at the desired point in the list with theInsert method:

    checkedListBox1.Items.Insert(0, "Copenhagen");
    

    - or -

  3. Assign an entire array to theItems collection:

    System.Object[] ItemObject = new System.Object[10];
    for (int i = 0; i <= 9; i++)
    {
       ItemObject[i] = "Item" + i;
    }
    listBox1.Items.AddRange(ItemObject);
    

To remove an item

  • Call theRemove orRemoveAt method to delete items.

    Remove has one argument that specifies the item to remove.RemoveAt removes the item with the specified index number.

    // To remove item with index 0:
    comboBox1.Items.RemoveAt(0);
    // To remove currently selected item:
    comboBox1.Items.Remove(comboBox1.SelectedItem);
    // To remove "Tokyo" item:
    comboBox1.Items.Remove("Tokyo");
    

To remove all items

  • Call the Clear method to remove all items from the collection:

    listBox1.Items.Clear();
    
Show:
© 2014 Microsoft