Redigera

Dela via


ListBox Control Overview (Windows Forms)

A Windows Forms ListBox control displays a list from which the user can select one or more items. If the total number of items exceeds the number that can be displayed, a scroll bar is automatically added to the ListBox control. When the MultiColumn property is set to true, the list box displays items in multiple columns and a horizontal scroll bar appears. When the MultiColumn property is set to false, the list box displays items in a single column and a vertical scroll bar appears. When ScrollAlwaysVisible is set to true, the scroll bar appears regardless of the number of items. The SelectionMode property determines how many list items can be selected at a time.

Ways to Change the ListBox Control

The SelectedIndex property returns an integer value that corresponds to the first selected item in the list box. You can programmatically change the selected item by changing the SelectedIndex value in code; the corresponding item in the list will appear highlighted on the Windows Form. If no item is selected, the SelectedIndex value is -1. If the first item in the list is selected, the SelectedIndex value is 0. When multiple items are selected, the SelectedIndex value reflects the selected item that appears first in the list. The SelectedItem property is similar to SelectedIndex, but returns the item itself, usually a string value. The Count property reflects the number of items in the list, and the value of the Count property is always one more than the largest possible SelectedIndex value because SelectedIndex is zero-based.

To add or delete items in a ListBox control, use the Add, Insert, Clear or Remove method. Alternatively, you can add items to the list by using the Items property at design time.

See also