Home Articles Books Downloads FAQs Tips

Q: Select an item in a ListBox or a ComboBox from code.


Answer:

For ComboBox and single selection ListBox controls, you select an item by assigning a number to the ItemIndex property of the ListBox or ComboBox. Assigning a value of zero selects the first item. Assigning -1 unselects all items.

    // single selection ListBox examples
    ListBox1->ItemIndex = 0;   // selects first item
    ListBox1->ItemIndex = 2;   // selects third item
    ListBox1->ItemIndex++;     // selects next item down
    ListBox1->ItemIndex = -1;  // unselects all items

If you would rather select an item by specifying a string, use the IndexOf function to return the index of a string, and then assign that index to the ItemIndex property. Selecting the item who's text is "Uncle Bob" would look like this:

  ListBox1->ItemIndex = ListBox1->Items->IndexOf("Uncle Bob");

For multi-select ListBox controls, you select and unselect items by reading and writing to the Selected property of the ListBox. The Selected property functions as an array of bool. The index of the array corresponds to the index of an item in the ListBox. To select an item, set its Selected index value to true. Here are some code examples.

    // multi-selection ListBox examples.
    ListBox1->Selected[0] = true;  // adds the first item to the selection
    ListBox1->Selected[0] = false; // removes first item from the selection

    // toggles the 10th item
    ListBox1->Selected[9] = !ListBox1->Selected[9]

    // selects a range of items
    for (int j=10; j<=19; j++)
        ListBox1->Selected[j] = true;

Note: Reading a value from the Selected array of a multi-select ListBox tells you if an item is currently selected. A value of true means that the item is selected, and false means that the item is not selected. Writing to the Selected array sets the selection status of an item. Writing to the Selected array selects an item if you assign true, and it unselects an item if you assign false. Reading or writing to one item in the ListBox does not affect other items in the ListBox.

Note: Do not use the Selected array in single selection ListBox controls

Note: In multi-select ListBox controls, you can read the ItemIndex property to determine which ListBox item has the input focus. However, assigning a value to ItemIndex has no effect in multi-select ListBox controls. When you write a value to ItemIndex, the VCL sends an LB_SETCURSEL to the ListBox control. Multi-select ListBox controls ignore this message. See the Win32 API help for more info.



Copyright © 1997-2000 by Harold Howe.
All rights reserved.