70-526 MCTS


ListBox

The ListBox control is used to provide a list of items from which the user may select one or more items. If a list box contains more items than can be displayed at one time, a vertical scroll bar is automatically added.


Inheritance hierarchy

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Windows.Forms.Control
        System.Windows.Forms.ListControl
          System.Windows.Forms.ListBox

Useful properties

  • ColumnWidth - Defines the width of columns in a multicolumn ListBox.
  • IntegralHeight - Indicates whether the control should resize to avoid showing partial items. (You may want to set this property to false, as when set to true, the ListBox looks really jerky if it is docked within a container and the container is resized.)
  • MultiColumn - Indicates whether the ListBox supports multiple columns.
  • SelectedIndices - Gets a collection that contains the zero-based indexes of all currently selected items in the ListBox.
  • SelectedItems - Gets a collection containing the currently selected items in the ListBox.
  • SelectionMode - Defines the method in which items are selected in the ListBox. Takes a value from the SelectionMode enumeration:
    • MultiExtended - Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections.
    • MultiSimple - Multiple items can be selected.
    • None - No items can be selected.
    • One - Only one item can be selected.


    Useful methods

  • ClearSelected - Unselects all items in the ListBox.
  • SetSelected - Selects or clears the selection for the specified item in a ListBox.

  • Displaying Items

    When strings are added to the Items collection, a scroll bar is automatically added to the right hand side of the control.

    The size and position of the bar within the scroll bar gives a good indication of how big the list is.


    Multi-column ListBox

    Often when a list becomes too long, it is beneficial to show multiple columns. This is achieved by setting the MultiColumn property to true.

    listBox1.MultiColumn = true;

    The width of the columns can be changed by setting the ColumnWidth property to a width in pixels.

    listBox1.ColumnWidth = 60;


    Selecting Items manually

    An item can be selected through code, by using the SelectedItem property.

    listBox1.SelectedItem = "Nickelback";

    More than one item can be selected by setting the SelectedItem property multiple times.

    listBox1.SelectedItem = "Nickelback";
    listBox1.SelectedItem = "Bee Gees";

    This only applies if the SelectionMode property is set to either MultiExtended or MultiSimple.

    Items can also be selected through the SelectedIndex property in the same manner.

    Note:
    An exception will be thrown if the item does not exist.

    MSDN references

  • ListBox Control Overview

  • << Previous Contents Next >>

    © Publicjoe, 2007