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

270 Chapter 6 BASIC WINDOWS CONTROLS

To iterate through all the selected items in a multiselection ListBox control, use a loop like the following:

Dim itm As Object

For Each itm In ListBox1.SelectedItems

Console.WriteLine(itm)

Next

The itm variable was declared as Object because the items in the ListBox control are objects. They happen to be strings in most cases, but they can be anything. If they’re all of the same type, you can convert them to the specific type and then call their methods. If all the items are of the Color type, you can use a loop like the following to print the red component of each color:

Dim itm As Object

For Each itm In ListBox1.SelectedItems

Console.WriteLine(Ctype(itm, Color).Red)

Next

A common situation in programming the ListBox control is to remove items from one control and add them to another. This is what the ListDemo project of the following section demonstrates, along with the techniques for adding and removing items to single-selection and a multiselection ListBox controls.

Note Even though the ListBox control can store all types of objects, it’s used most frequently for storing strings. Storing objects to a ListBox control requires some extra work, because the ToString method of most objects doesn’t return the type of string we want to display on the control. You will find an example on using the ListBox control with objects in Chapter 8, where you’ll learn how to build custom objects.

VB.NET at Work: The ListDemo Project

The ListDemo application (shown in Figure 6.7) demonstrates the basic operations of the ListBox control. The two ListBox controls on the form operate slightly differently. The first has the default configuration: only one item can be selected at a time, and new items are appended after the existing item. The second ListBox control has its Sorted property set to True and its MultiSelect property set to MultiExtended. This means that the elements of this control are always sorted, and the user can select multiple cells with the mouse.

The code for the ListDemo application contains much of the logic you’ll need in your ListBox manipulation routines. It shows you how to:

Add and remove items

Transfer items between lists

Handle multiple selected items

Maintain sorted lists

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 271

Figure 6.7

ListDemo demonstrates most of the operations you’ll perform with ListBoxes.

The Add Item Buttons

The Add Item buttons use the InputBox() function to prompt the user for input, and then they add the user-supplied string to the ListBox control. The code is identical for both buttons (Listing 6.10).

Listing 6.10: The Add Item Buttons

Private Sub bttnAdd1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnAdd1.Click Dim ListItem As String

ListItem = InputBox(“Enter new item’s name”) If ListItem.Trim <> “” Then

sourceList.Items.Add(ListItem) End If

End Sub

Notice that the subroutine examines the data entered by the user to avoid adding blank strings to the list. The code for the Clear buttons is also straightforward; it simply calls the Clear method of the Items collection to remove all entries from the corresponding list.

The Remove Selected Item(s) Buttons

The code for the Remove Selected Item button is different from that for the Remove Selected Items button (both are presented in Listing 6.11). The code for the Remove Selected Items button must scan all the items of the left list and remove the selected one(s). The reason is that the ListBox on the right can have only one selected item, and the other one allows the selection of multiple items. To delete an item, you must have at least one item selected. The code makes sure that the SelectedIndex property is not negative. If no item is selected, the SelectedIndex property is –1 and attempting to remove an item by specifying an invalid index will generate an error.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

272 Chapter 6 BASIC WINDOWS CONTROLS

Listing 6.11: The Remove Buttons

Private Sub bttnRemoveSelDest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnRemoveSelDest.Click destinationList.Items.Remove(destinationList.SelectedItem)

End Sub

Private Sub bttnRemoveSelSrc_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnRemoveSelSrc.Click Dim i As Integer

For i = 0 To sourceList.SelectedIndices.Count - 1 sourceList.Items.RemoveAt(sourceList.SelectedIndices(0))

Next End Sub

Even though it’s possible to remove an item by name, this is not a safe approach. If two items have the same name, then the Remove method will remove the first one. Unless you’ve provided the code to make sure that no identical items can be added to the list, remove them by their index, which is unique.

Notice that the code removes always the first item in the SelectedIndices collection. If you attempt to remove the item SelectedIndices(i), you will remove the first selected item, but after that you will not remove all the selected items. After removing an item from the selection, the remaining items are no longer at the same locations. The second selected item will take the place of the first selected item, which was just deleted, and so on. By removing the first item in the SelectedIndices collection, we make sure that all selected items, and only they, will be eventually removed.

The code of the Remove Selected Items button uses the Count property of the SelectedIndices collection to repeat the operation as many times as the number of selected items.

The Arrow Buttons

The two Buttons with the single arrows, between the ListBox controls shown in Figure 6.7, transfer selected items from one list to another. The first arrow button can transfer a single element only, after it ensures that the list contains a selected item. Its code is presented in Listing 6.12. First, it adds the item to the second list, and then it removes the item from the original list. Notice that the code removes an item by passing it as argument to the Remove method, because it doesn’t make any difference which one of two identical objects will be removed.

Listing 6.12: The Right Arrow Button

Private Sub bttnMoveDest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnMoveDest.Click Dim i As Integer

While sourceList.SelectedIndices.Count > 0 destinationList.Items.Add(sourceList.SelectedItems(i)) sourceList.Items.Remove(sourceList.SelectedItems(i))

End While End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE LISTBOX, CHECKEDLISTBOX, AND COMBOBOX CONTROLS 273

The second arrow button transfers items in the opposite direction; the code is almost identical to the one presented here, and I need not repeat it. The fact that one list is sorted and the other isn’t doesn’t affect our code. The destination control (the one on the left) doesn’t allow the selection of multiple items, so you could use the SelectedIndex and SelectedItem properties. Since the single element is also part of the SelectedItems collection, you need not use a different approach. The statements that move a single item from the right to the left ListBox are shown next:

sourceList.Items.Add(destinationList.SelectedItem)

destinationList.Items.RemoveAt(destinationList.SelectedIndex)

Before we leave the topic of the ListBox control, let’s examine one more powerful technique: using the ListBox control to maintain a list of keys (the data items used in recalling the information) to an array or random access file with records of related information. We’ll use the ListBox control to store information like names, or book titles, which allows users to select the desired item. The item in the control will be linked to related information, like addresses and phone numbers for people, author and price information for books, and so on. In other words, we’ll use the ListBox control as a lookup mechanism for several pieces of information.

Searching

The single most important enhancement to the ListBox control is that it can now locate any item in the list with the FindString and FindStringExact methods. Both methods accept a string as argument (the item to be located) and a second, optional argument, the index at which the search will begin.

The FindString method locates a string that partially matches the one you’re searching for; FindStringExact finds an exact match. If you’re searching for “Man” and the control contains a name like “Mansfield,” FindString will match the item, but FindStringExact will not.

Note Both the FindString and FindStringExact methods perform case-insensitive searches. If you’re searching for “visual” and the list contains the item “Visual”, both methods will locate it.

The syntax of both methods is the same:

itemIndex = ListBox1.FindString(searchStr As String)

where searchStr is the string you’re searching for. An alternative form of both methods allows you to specify the order of the item at which the search will begin:

itemIndex = ListBox1.FindString(searchStr As String, startIndex As Integer)

The startIndex argument allows you specify the beginning of the search, but you can’t specify where the search will end.

The FindString and FindStringExact methods work even if the ListBox control is not sorted. You need not set the Sorted property to True before you call one of the searching methods on the control. Sorting the list will probably help the search operation a little, but it takes the control less than 100 milliseconds to find an item in a list of 100,000 items, so time spent to sort the list isn’t worth it.

VB.NET at Work: The ListBoxFind Application

The application you’ll build in this section (seen in Figure 6.8) populates a list with a large number of items and then locates any string you specify. Click the button Populate List to populate the

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

274 Chapter 6 BASIC WINDOWS CONTROLS

ListBox control with 10,000 random strings. This process will take a few seconds and will populate the control with different random strings every time. Then, each time you click the Find Item button, you’ll be prompted to enter a string. The code will locate the closest match in the list and select (highlight) this item.

Figure 6.8

The ListBoxFind application

The code (Listing 6.13) attempts to locate an exact match with the FindStringExact method. If it succeeds, it reports the index of the matching element. If not, it attempts to locate a near match, with the FindString method. If it succeeds, it reports the index of the near match (which is the first item on the control that partially matches the search argument) and terminates. If it fails to find an exact match, it reports that the string wasn’t found in the list.

Listing 6.13: Searching the List

Private Sub bttnFind_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnFind.Click

Dim srchWord As String

 

Dim wordIndex As Integer

 

srchWord = InputBox(“Enter word to search for”)

 

wordIndex = ListBox1.FindStringExact(srchWord)

 

If wordIndex >= 0 Then

 

MsgBox(“Index = “ & wordIndex.ToString & “

=” & _

(ListBox1.Items(wordIndex)).ToString, , “EXACT MATCH”)

ListBox1.TopIndex = wordIndex

 

ListBox1.SelectedIndex = wordIndex

 

Else

 

wordIndex = ListBox1.FindString(srchWord)

 

If wordIndex >= 0 Then

 

MsgBox(“Index = “ & wordIndex.ToString & “

=” & _

(ListBox1.Items(wordIndex)).ToString, , “NEAR MATCH”) ListBox1.TopIndex = wordIndex

ListBox1.SelectedIndex = wordIndex Else

MsgBox(“Item “ & srchWord & “ is not in the list”) End If

End If End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com