70-526 MCTS


Provide a list of options on a Windows Form by using a ListBox control, a ComboBox control, or a CheckedListBox control

List controls are used to present lists of data to a user from which an option can be chosen. This section deals with three of those controls, namely ListBox, ComboBox and CheckedListBox. Each of these control inherit (directly or indirectly) from the abstract ListControl class.

The ListControl class defines functionality allowing you to use a list control with data binding. Each of these controls can be bound to objects such as DataSets, arrays, and ArrayList collections.

The controls differ in their appearance and functionality, but the organisation and presentation of data is much the same. Each control contains objects that are held in a collection called Items. Each of these items is displayed in the control as a string or string representation when the item is not a string.

  • The ListBox is used to provide a list of items from which the user may select one or more items.
  • The ComboBox combines a ListBox control with a TextBox control.
  • The CheckedListBox displays a ListBox in which a check box is displayed to the left of each item.

Common useful properties

  • DataSource - Defines the data source for data binding in this ListControl.

  • DisplayMember - Defines the data member that is displayed in this ListControl.

  • FormatString - Defines the format-specifier characters that indicate how a value is to be displayed if FormattingEnabled is set to true.

  • FormattingEnabled - Indicates whether formatting is applied to the DisplayMember property of the ListControl.

  • IntegralHeight - Indicates whether the control should resize to avoid showing partial items. When this property is set to true, the control automatically resizes to ensure that an item is not partially displayed.

  • Items - The collection of items of the ListControl.

  • SelectedIndex - Defines the zero-based index of the currently selected item in a ListControl.

  • SelectedItem - Defines the currently selected item in the ListControl.

  • SelectedValue - Defines the value of the member property specified by the ValueMember property.

  • Sorted - Indicates whether the items in the ListControl are sorted alphabetically.

  • ValueMember - Defines the property to use as the actual value for the items in the ListControl.


    Common useful methods

  • FindString - Finds the first item in the ListControl that starts with the specified string.

  • FindStringExact - Finds the first item in the ListControl that exactly matches the specified string.


    Adding Items to the Item list

    To add items to the Items collection, you use the String Collection Editor. The editor can be displayed from the Properties window of a ListControl child control by clicking the Ellipsis () button next to the Items property of the control. Alternatively, you can click on the smart tag icon on a ListControl child control in the designer and choose Edit Items.

    Strings can then be added one per line.


    Adding Items to the Item list manually

    To add items to the list through code, simply use the Add method of the Items collection.

    listBox1.Items.Add("Click Me");

    Alternatively you can add several items at once using the AddRange method of the Items collection.

    listBox1.Items.AddRange(new String[]{"Blue", "Red", "Yellow"});

    Items are added to the bottom of the list.


    Inserting Items into the Item list manually

    Items can be inserted into the list through code, by using the Insert method of the Items collection.

    listBox1.Items.Insert(0, "Nickelback");

    When an item is inserted into the list at a location that is already occupied, then that item and any beneath it are shifted down one index.


    Removing Items from the Item list manually

    Items can be removed from the list through code, by using either the Remove method of the Items collection.

    listBox1.Items.Remove("Click Me");

    or if you do not know the text, but know the index from which you want to remove an item, you can use the RemoveAt method.

    listBox1.Items.RemoveAt(2);

    Removing all Items from the Item list manually

    All Items can be removed from the list through code, by using the Clear method of the Items collection.

    listBox1.Items.Clear();

    Determining the Selected Item

    Whenever the user clicks on an item in the list, the SelectedIndexChanged event is fired. Before doing anything within this event it is a wise move to find out which of the items has been selected. This can be simply achieved through the SelectedIndex property.

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      int iIndex = 0;
    
      if(listBox1.SelectedIndex != -1 )
      {
        iIndex = listBox1.SelectedIndex;
      }
    }

    Sorting Items

    Items can be sorted in a ListControl by setting the Sorted property to true.

    listBox1.Sorted = true;

    Formatting Items

    Items can be formatted through the FormatString property at design time. This is achieved through the Format String Dialog editor. The editor can be displayed from the Properties window of a ListControl child control by clicking the Ellipsis () button next to the FormatString property of the control.

    The FormattingEnabled property determines whether formatting is applied to the DisplayMember property of the ListControl. The MSDN page for Custom Numeric Format Strings has the following table for customising strings.

    Format specifier Name Description
    0 Zero placeholder

    If the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the result string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the result string.

    The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.

    # Digit placeholder

    If the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string.

    Note that this specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed.

    The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.

    . Decimal point

    The first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored.

    The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo that controls formatting.
    , Thousand separator and number scaling

    The ',' character serves as both a thousand separator specifier and a number scaling specifier.

    Thousand separator specifier: If one or more ',' characters is specified between two digit placeholders (0 or #) that format the integral digits of a number, a group separator character is inserted between each number group in the integral part of the output.

    The NumberGroupSeparator and NumberGroupSizes properties of the current NumberFormatInfo object determine the character used as the number group separator and the size of each number group. For example, if the string "#,#" and the invariant culture are used to format the number 1000, the output is "1,000".

    Number scaling specifier: If one or more ',' characters is specified immediately to the left of the explicit or implicit decimal point, the number to be formatted is divided by 1000 each time a number scaling specifier occurs. For example, if the string "0,," is used to format the number 100 million, the output is "100".

    You can use thousand separator and number scaling specifiers in the same format string. For example, if the string "#,0,," and the invariant culture are used to format the number one billion, the output is "1,000".

    % Percentage placeholder The presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.
    E0 E+0 E-0 e0 e+0 e-0 Scientific notation If any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The "E+" and "e+" formats indicate that a sign character (plus or minus) should always precede the exponent. The "E", "E-", "e", or "e-" formats indicate that a sign character should only precede negative exponents.
    \ Escape character

    In C# and C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like '\n' (new line).

    In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display '\'.

    'ABC' "ABC" Literal string Characters enclosed in single or double quotes are copied to the result string, and do not affect formatting.
    ; Section separator The ';' character is used to separate sections for positive, negative, and zero numbers in the format string.
    Other All other characters Any other character is copied to the result string, and does not affect formatting.


    MSDN references

  • ListBox control
  • CheckedListBox control
  • ComboBox control
  • Building a Better ComboBox
  • Windows Forms Controls Used to List Options
  • Custom Numeric Format Strings
    << Previous Contents Next >>

    © Publicjoe, 2007