Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 263

With a little additional effort, you can provide users with a dialog box that lets them assign their own strings to function keys. You’ll probably have to take into consideration the status of the Shift, Control, and Alt properties of the event’s e argument, which report the status of the Shift, Ctrl, and Alt keys respectively. Windows already uses many of the function keys, and you shouldn’t reassign them. For example, the F1 key is the standard Windows context-sensitive Help key, and users will be confused if they press F1 and see the date appear in their documents. The keystroke Alt+F4 closes the window, so you shouldn’t reassign it either.

To find out whether two of the modifier keys are down when a key is pressed, use the AND operator with the appropriate properties of the e argument. The following If structure detects the Ctrl and Alt keys:

If e.Control AND e.Alt Then

{ Alt and Control keys were down } End If

The ListBox, CheckedListBox, and ComboBox Controls

The ListBox, CheckedListBox, and ComboBox controls present lists of choices, from which the user can select one or more. The first two are illustrated in Figure 6.6. The ListBox control occupies a user-specified amount of space on the form and is populated with a list of items. If the list of items is longer than can fit on the control, a vertical scroll bar appears automatically.

Figure 6.6

The ListBox and CheckedListBox controls

The items must be inserted in the ListBox control through the code or via the Properties window. To add items at design time, locate the Items property in the control’s Properties window and click the button with the ellipsis. A new window will pop up, the String Collection Editor window, where you can add the items you want to display on the list. Each item must appear on a separate text line, and blank text lines will result in blank lines on the list. These items will appear on the list when the form is loaded, but you can add more items (or remove existing ones) from within your code at any time. They will appear in the same order as entered on the String Collection Editor window unless the control has its Sorted property set to True, in which case the items will be automatically sorted, regardless of the order in which you’ve specified them.

The ComboBox control also contains multiple items but typically occupies less space on the screen. The ComboBox control is an expandable ListBox control: the user can expand it to make a selection and collapse it after the selection is made. The real advantage to the ComboBox control, however, is that the user can enter new information in the ComboBox, rather than being forced to select from the items listed.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

264 Chapter 6 BASIC WINDOWS CONTROLS

This section first examines the ListBox control’s properties and methods. Later, you’ll see how the same properties and methods can be used with the ComboBox control.

There’s also a variation of the ListBox control, the CheckedListBox control, which is identical to the ListBox control, but a check box appears in front of each item. The user can select any number of items by checking the boxes in front of them.

VB6 VB.NET

The ListBox control has been greatly enhanced in .NET Framework. The most prominent change is that it no longer supports the List property. To access individual items on the control, you must use the Items property, which is a Collection. The first item on the control is Items(0), the second is Items(1), and so on. The Items collection has the usual properties of a collection: the Count property, which is the number of items on the control, and the Add, Remove, Insert, and Clear methods to add items to or remove items from the control. The ListCount property has also disappeared. The number of items on the control is given by the expression Items.Count, and the AddItem and RemoveItem methods of the old version of the control are no longer supported.

The handling of multiple selected items has also been enhanced. If the control allows a single selection, the SelectedIndex and SelectedItem properties return the index and the value of the selected item. If the control allows multiple selections, you can use the SelectedIndices and SelectedItems collections to access the indices and values of the selected items.

The most important enhancement to the new ListBox control is the search feature. You can use the FindString and FindStringExact methods to locate an item in the list. The FindString method locates the closest match to the search argument, while the FindStringExact method finds an exact match, if there is one. Notice that these methods work just as well with sorted and unsorted lists.

Finally, two new methods were introduced to speed up the display while new items are added to the control. If you have many items to add to the control at once, call the BeginUpdate method at the beginning, then call the Add or Insert method of the Items collection as many times as needed, and finally call the EndUpdate method. The control won’t be updated each time you add a new item, but the items will be added to the control after EndUpdate is executed. This technique avoids the constant flickering of the control while new items are added.

Basic Properties

The ListBox and ComboBox controls provide a few common properties that determine the basic functionality of the control and are usually set at design time; we’ll start with these fundamental properties.

IntegralHeight

This property is a Boolean value (True/False) that indicates whether the control’s height will be adjusted to avoid the partial display of the last item. When set to True, the control’s actual height may be slightly different than the size you’ve specified, so that only an integer number of rows are displayed. If you want the ListBox control be the same height as another control, use the ListBox as the reference for the other controls. Sometimes you’ll have to set this property to False to align a ListBox control with other controls on the form.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 265

Items

The Items property is a collection that holds the items on the control. At design time, you can populate this list through the String Collection Editor window. At runtime you can access and manipulate the items through the methods and properties of the Items collection, which are described in the following section. To load a number of items to a ListBox control at design time, locate the Items property in the Properties window, and click the button with the ellipsis next to it. This will bring up the String Collection Editor, where you can enter any number of items. Enter each item’s text on a separate line, and click the OK button when you’re done to close the window.

MultiColumn

A ListBox control can display its items in multiple columns, if you set its MultiColumn property to True. The problem with multicolumn ListBoxes is that you can’t specify the column in which each item will appear. Set this property to True for ListBox controls with a relatively small number of items, and do so only when you want to save space on the form. A horizontal scroll bar will be attached to a multicolumn ListBox, so that users can bring any column into view.

SelectionMode

This property determines how the user can select the list’s items and must be set at design time (at runtime, you can only read this property’s value). The SelectionMode property’s values determine whether the user can select multiple items and which method will be used for multiple selections.

The possible values of this property—members of the SelectionMode enumeration—are shown in Table 6.2.

Table 6.2: The SelectionMode Enumeration

Value

Description

None

No selection at all is allowed.

One

(Default) Only a single item can be selected.

MultiSimple

Simple multiple selection: A mouse click (or pressing the spacebar) selects or deselects

 

an item in the list. You must click all the items you want to select.

MultiExtended

Extended multiple selection: Press Shift and click the mouse (or press one of the arrow

 

keys) to expand the selection. This will highlight all the items between the previously

 

selected item and the current selection. Press Ctrl and click the mouse to select or dese-

 

lect single items in the list.

 

 

Sorted

Items can be inserted by the application into a ListBox or ComboBox control, but inserting them in the proper place and maintaining some sort of organization can be quite a task for the programmer. If you want the items to be always sorted, set the control’s Sorted property to True. This property can be set at design time as well as runtime.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

266 Chapter 6 BASIC WINDOWS CONTROLS

The ListBox control is basically a text control and won’t sort numeric data properly. To use the ListBox control to sort numbers, you must first format them with leading zeros. For example, the number 10 will appear in front of the number 5, because the string “10” is smaller than the string “5”. If the numbers are formatted as “010” and “005”, they will be sorted correctly.

The items in a sorted ListBox control are in ascending and case-sensitive order. Moreover, there is no mechanism for changing this default setting. The following items would be sorted as shown:

“AA”

“Aa”

“aA”

“aa”

“BA”

“ba”

Uppercase characters appear before the equivalent lowercase characters, but both upperand lowercase characters appear together. All words beginning with B appear after the words beginning with A and before the words beginning with C. Within the group of words beginning with B, those beginning with a capital B appear before those beginning with a lowercase b.

Note Populating long sorted lists is an expensive operation, because VB must figure out where to insert each item. It takes 13 seconds to populate an unsorted list with 100,000 items. The same operation takes forever (several minutes) if the Sorted property is set to True. If you want to add a large number of items to a ListBox control, set its Sorted property to False, populate it and then set the Sorted property to True to sort the items on the control. For 100,000 items, this trick will bring down the total time from minutes to seconds.

Text

The Text property returns the selected text on the control. Notice that the items need not be strings. By default, each item is an object. For each object, however, the control displays a string, which is the same string returned by the object’s ToString method. To retrieve the selected string on the control, use the Text property. To access the actual object, use the SelectedItem property, which is described later in this chapter.

The Items Collection

To manipulate a ListBox control from within your application, you should be able to:

Add items to the list

Remove items from the list

Access individual items in the list

The items in the list are represented by the Items collection. You use the members of the Items collection to access the control’s items and to add or remove items. The Items property exposes the standard members of a Collection, and they’re described in the following sections.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 267

Each member of the Items collection is an object. In most cases, we use ListBox controls to store strings, but it’s possible to store objects. When you add an object to a ListBox control, a string will be displayed on the corresponding line of the control. This is the string returned by the object’s ToString method. This is the property of the object that will be displayed by default. You can display any other property of the object by setting the control’s ValueMember property to the name of the property.

If you add a Color and a Rectangle object to the Items collection with the following statements:

ListBox1.Items.Add(Color.Yellow)

ListBox1.Items.Add(New Rectangle(0, 0, 100, 100))

then the following strings will appear on the first two lines of the control:

Color [Yellow]

{X=0, Y=0, Width=100, Height=100}

However, you can access the members of the two objects, because the ListBox stores objects, not their descriptions. The following two statements will print the green color component of the Color object and the width of the Rectangle object (the output produced by each statement is shown in bold):

Console.WriteLine(ListBox1.Items.Item(0).G)

255

Console.WriteLine(ListBox1.Items.Item(1).Width)

100

The expressions in the last two statements are late-bound. This means that the compiler doesn’t know whether the first object in the Items collection is a Color object and therefore can’t verify the member Green. If you attempt to call the Green property of the second item in the collection, you’ll get an exception at runtime to the effect that the code has attempted to access a missing member. The missing member is the G (green component) property of the Rectangle object.

The proper way to read the objects stored in a ListBox control is to examine the type of the object first, and attempt to retrieve a property (or call a method) of the object only if it’s of the appropriate type. Here’s how you would read the green component of a Color object:

If ListBox1.Items.Item(0).GetType Is GetType(Color) Then

Console.WriteLine(ListBox1.Items.Item(0).G)

End If

Add

To add items to the list, use the Items.Add or Items.Insert method. The syntax of the Add method is

ListBox1.Items.Add(item)

The item parameter is the object to be added to the list. You can add any object to the ListBox control, but items are usually strings. The Add method appends new items to the end of the list, unless the Sorted property has been set to True.

The following loop adds the elements of the array words to a ListBox control, one at a time:

Dim words(100) As String

{ statements to populate array }

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

268 Chapter 6 BASIC WINDOWS CONTROLS

Dim i As Integer

For i = 0 To 99

ListBox1.Items.Add(words(i))

Next

Similarly, you can iterate through all the items on the control with a loop like the following:

Dim i As Integer

For i = 0 To ListBox1.Items.Count – 1

{ statements to process item ListBox1.Items(i) }

Next

You can also use the For Each…Next statement to iterate through the Items collection, as shown here:

Dim itm As Object

For Each itm In ListBox1.Items

{ process the current item, represented by the itm variable } Next

When you populate a ListBox control with a large number of items, call the BeginUpdate before starting the loop and the EndUpdate method when you’re done. These two methods will turn off the visual update of the control while you’re populating it. When the EndUpdate method is called, the control will be redrawn with all the items.

Clear

The Clear method removes all the items from the control. Its syntax is quite simple:

List1.Items.Clear

Count

This is the number of items in the list. If you want to access all the items with a For…Next loop, the loop’s counter must go from 0 to ListBox1.Items.Count – 1, as shown in the example of the Add method.

CopyTo

The CopyTo method of the Items collection retrieves all the items from a ListBox control and stores them to the array passed to the method as argument. The syntax of the CopyTo method is

ListBox1.CopyTo(destination, index)

where destination is the name of the array that will accept the items and index is the index of an element in the array where the first item will be stored. The array that will hold the items of the control must be declared explicitly and must be large enough to hold all the items.

Insert

To insert an item at a specific location, use the Insert method, whose syntax is:

ListBox1.Items.Insert(index, item)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 269

where item is the object to be added and index is the location of the new item. The first item’s order in the list is zero. Note that you need not insert items at specific location when the list is sorted. If you do, the items will be inserted at the specified locations, but the list will no longer be sorted.

The following statement inserts a new item at the top of the list:

ListBox1.Items.Insert(0, “new item”)

Remove

To remove an item from the list, you must first find its position (index) in the list, and call the Remove method passing the position as argument:

ListBox1.Items.Remove(index)

The index parameter is the order of the item to be removed, and this time it’s not optional. The following statement removes the item at the top of the list:

ListBox1.Remove(0)

You can also specify the item to be removed by reference. To remove a specific item from the list, use the following syntax:

ListBox1.Items.Remove(item)

If the control contains strings, pass the string to be removed. If the same string appears multiple times on the control, only the first instance will be removed. If the control contains object, pass a variable that references the item you want to remove.

Contains

The Contains method of the Items collection—not to be confused with the control’s Contains method—accepts an object as argument and returns a True/False value indicating whether the collection contains this object or not. Use the Contains method to avoid the insertion of identical objects to the ListBox control. The following statements add a string to the Items collection, only if the string isn’t already part of the collection:

Dim itm As String = “Remote Computing”

If Not ListBox1.Items.Contains(itm) Then

ListBox1.Items.Add(itm)

End If

Selecting Items

The ListBox control allows the user to select either one or multiple items, depending on the setting of the SelectionMode property. In a single-selection ListBox control, you can retrieve the selected item with the SelectedItem property and its index with the SelectedIndex property. SelectedItem returns the selected item, which could be an object. The text that was clicked by the user to select the item is reported by the Text property.

If the control allows the selection of multiple items, they’re reported with the SelectedItems property. This property is a collection of Item objects and exposes the same members as the Items collection. The SelectedItems.Count property reports the number of selected items.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com