15.6 ListBox Control

The ListBox control allows the user to view and select from multiple items in a list. List-Boxes are static GUI entities, which means that users cannot directly edit the list of items. The user can be provided with TextBoxes and Buttons with which to specify items to be added to the list, but the actual additions must be performed in code. The CheckedListBox control (Section 15.7) extends a ListBox by including CheckBoxes next to each item in the list. This allows users to place checks on multiple items at once, as is possible with CheckBox controls. (Users also can select multiple items from a ListBox by setting the ListBox’s SelectionMode property, which is discussed shortly.) Figure. 15.15 displays a ListBox and a CheckedListBox. In both controls, scrollbars appear if the number of items exceeds the ListBox’s viewable area.

Fig. 15.15 ListBox and CheckedListBox on a Form.

Figure. 15.16 lists common ListBox properties and methods and a common event. The SelectionMode property determines the number of items that can be selected. This property has the possible values None, One, MultiSimple and MultiExtended (from the SelectionMode enumeration)—the differences among these settings are explained in Fig. 15.16. The SelectedIndexChanged event occurs when the user selects a new item.

Fig. 15.16 ListBox properties, methods and an event.

ListBox properties, methods and an event Description
Common Properties
Items The collection of items in the ListBox.
MultiColumn Indicates whether the ListBox can display multiple columns. Multiple columns eliminate vertical scrollbars from the display.
SelectedIndex Returns the index of the selected item. If no items have been selected, the property returns -1. If the user selects multiple items, this property returns only one of the selected indices. If multiple items are selected, use property SelectedIndices.
SelectedIndices Returns a collection containing the indices for all selected items.
SelectedItem Returns a reference to the selected item. If multiple items are selected, it can return any of the selected items.
SelectedItems Returns a collection of the selected item(s).
SelectionMode Determines the number of items that can be selected and the means through which multiple items can be selected. Values are None, One (the default), MultiSimple (multiple selection allowed) or MultiExtended (multiple selection allowed using a combination of arrow keys or mouse clicks and Shift and Ctrl keys).
Sorted Indicates whether items are sorted alphabetically. Setting this property’s value to true sorts the items. The default value is false.
Common Methods
ClearSelected Deselects every item.
GetSelected Returns true if the item at the specified index is selected.
Common Event
SelectedIndexChanged Generated when the selected index changes. This is the default event when the control is double clicked in the designer.

Both the ListBox and CheckedListBox have properties Items, SelectedItem and SelectedIndex. Property Items returns a collection of the list items. Collections are a common way to manage lists of objects in the .NET framework. Many .NET GUI components (e.g., ListBoxes) use collections to expose lists of internal objects (e.g., items in a ListBox). We discuss collections further in Chapter 21. The collection returned by property Items is represented as an object of type ListBox.ObjectCollection. Property SelectedItem returns the ListBox’s currently selected item. If the user can select multiple items, use collection SelectedItems to return all the selected items as a ListBox.Select-edObjectColection. Property SelectedIndex returns the index of the selected item—if there could be more than one, use property SelectedIndices, which returns a ListBox.SelectedIndexCollection. If no items are selected, property SelectedIndex returns -1. Method GetSelected takes an index and returns true if the corresponding item is selected.

Adding Items to ListBoxes and CheckedListBoxes

To add items to a ListBox or to a CheckedListBox, we must add objects to its Items collection. This can be accomplished by calling method Add to add a string to the ListBox’s or CheckedListBox’s Items collection. For example, we could write


myListBox.Items.Add(myListItem);

to add string myListItem to ListBox myListBox. To add multiple objects, you can either call method Add multiple times or call method AddRange to add an array of objects. Classes ListBox and CheckedListBox each call the submitted object’s ToString method to determine the Label for the corresponding object’s entry in the list. This allows you to add different objects to a ListBox or a CheckedListBox that later can be returned through properties SelectedItem and SelectedItems.

Alternatively, you can add items to ListBoxes and CheckedListBoxes visually by examining the Items property in the Properties window. Clicking the ellipsis button opens the String Collection Editor, which contains a text area for adding items; each item appears on a separate line (Fig. 15.17). Visual Studio then writes code to add these strings to the Items collection inside method InitializeComponent.

Fig. 15.17 String Collection Editor.

Figure. 15.18 uses class ListBoxTestForm to add, remove and clear items from ListBox displayListBox. Class ListBoxTestForm uses TextBox inputTextBox to allow the user to type in a new item. When the user clicks the Add Button, the new item appears in displayListBox. Similarly, if the user selects an item and clicks Remove, the item is deleted. When clicked, Clear deletes all entries in displayListBox. The user terminates the app by clicking Exit.

The addButton_Click event handler (lines 20–24) calls method Add of the Items collection in the ListBox. This method takes a string as the item to add to displayListBox. In this case, the string used is the user input from the inputTextBox (line 22). After the item is added, inputTextBox.Text is cleared (line 23).

The removeButton_Click event handler (lines 27–34) uses method RemoveAt to remove an item from the ListBox. Event handler removeButton_Click first uses property SelectedIndex to determine which index is selected. If SelectedIndex is not –1 (i.e., an item is selected), line 32 removes the item that corresponds to the selected index.

Fig. 15.18 Program to add, remove and clear ListBox items.

Alternate View

  1    // Fig. 15.18: ListBoxTestForm.cs
  2    // Program to add, remove and clear ListBox items
  3    using System;
  4    using System.Windows.Forms;
  5
  6    namespace ListBoxTest
  7    {
  8       // Form uses a TextBox and Buttons to add,
  9       // remove, and clear ListBox items
 10       public partial class ListBoxTestForm : Form
 11       {
 12          // constructor
 13          public ListBoxTestForm()
 14          {
 15             InitializeComponent();
 16          }
 17
 18          // add new item to ListBox (text from input TextBox)
 19          // and clear input TextBox
 20          private void addButton_Click(object sender, EventArgs e)
 21          {
 22              displayListBox.Items.Add(inputTextBox.Text);
 23              inputTextBox.Clear();
 24          }
 25
 26          // remove item if one is selected
 27          private void removeButton_Click(object sender, EventArgs e)
 28          {
 29              // check whether item is selected; if so, remove
 30              if (displayListBox.SelectedIndex != -1)
 31              {
 32                 displayListBox.Items.RemoveAt(displayListBox.SelectedIndex);
 33              }
 34           }
 35
 36           // clear all items in ListBox
 37           private void clearButton_Click(object sender, EventArgs e)
 38           {
 39              displayListBox.Items.Clear();
 40           }
 41
 42           // exit app
 43           private void exitButton_Click(object sender, EventArgs e)
 44           {
 45              Application.Exit();
 46           }
 47        }
 48    }

The clearButton_Click event handler (lines 37–40) calls method Clear of the Items collection (line 39). This removes all the entries in displayListBox. Finally, event handler exitButton_Click (lines 43–46) terminates the app by calling method Application.Exit (line 45).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset