9.1. List Boxes, Combo Boxes, and the File-Opening ControlThroughout this book, we have used list boxes to display the output of a program. However, list boxes also provide a potent means for obtaining input by selecting an item from a list. Two other controls that allow us to choose an item from a list are the ComboBox and the OpenFileDialog controls. The List Box ControlThe list boxes discussed in this text display a single column of strings, referred to as items. The items to appear initially can either be specified at design time with the Items property or set with code in a procedure. Code is then used to access, add, or delete items from the list. We will first carry out all tasks with code and then show how the initial items can be specified at design time. At any time, the value of lstBox.Items.Count is the number of items in the list box. Each item in lstBox is identified by an index number ranging from 0 through lstBox.Items.Count - 1. The Sorted property is perhaps the most interesting list box property. When it is set to True, the items will automatically be displayed in alphabetical (i.e., ANSI) order. The default value of the Sorted property is False. When the Sorted property is set to True, the statement num = lstBox.Items.Add(str) inserts str into the list at the proper sorted position and assigns to the Integer variable num the index number of that position. During run time, you can highlight an item from a list by clicking on it with the mouse or by moving to it with the up- and down-arrow keys when the list box has the focus. (The second method triggers the SelectedIndexChanged event each time an arrow key causes the highlight to move.) The value of lstBox.SelectedIndex is the index number of the item currently highlighted in lstBox. If no item is highlighted, the value of SelectedIndex is1. The statement lstBox.ListIndex = -1 will unhighlight any highlighted item in the list. The list of items stored in the list box are held in lstBox.Items(). In particular, the value of lstBox.Items(n) is the item of lstBox having index n. The elements of the list are of a data type called Object. A variable of any type may be assigned to an element of the list. However, type casting must take place whenever an element of the list is assigned to a numeric or string variable or concatenated with another variable or literal. For instance, the statement txtBox.Text = CStr(lstBox.Items(0)) displays the first item of lstBox. The value of lstBox.Items(lstBox.SelectedIndex) is the item currently highlighted in lstBox. Alternatively, the value of lstBox.Text is also the currently highlighted item. Setting this property to a string value will select the item in the list box that matches the value. The statement lstBox.Items.RemoveAt(n) deletes the item of index n from lstBox, the statement lstBox.Items.Remove(str) deletes the first occurrence of the value of str in lstBox. When the user selects an item in a list box, an event is triggered. A program can respond to three main types of events. If the user clicks on an item, the Click event is processed. If the user clicks on a different item or uses the arrow keys to select it, the SelectedIndexChanged event is processed. If the user double-clicks on an item, then the Click, DoubleClick, and SelectedIndexChanged events are triggered. Example 1. |
An oxymoron is a pairing of contradictory or incongruous words. The following program displays a list of oxymorons. When you select an item, it is displayed in a text box. A button allows you to add an additional item with an input dialog box. You can delete an item by double-clicking on it with the mouse. After running the program, click on different items, add an item or two (such as "same difference" or "liquid gas"), and delete an item.
Private Sub lstOxys_SelectedIndexChanged(...) Handles _ lstOxys.SelectedIndexChanged txtSelected.Text = CStr(lstOxys.Text) End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim item As String item = InputBox("Item to Add:") lstOxys.Items.Add(item) End Sub Private Sub lstOxys_DoubleClick(...) Handles lstOxys.DoubleClick lstOxys.Items.RemoveAt(lstOxys.SelectedIndex) txtSelected.Clear() End Sub [Run, add some items and then click on an item of the list box.]
|
The following steps show how to fill a list box at design time. (This method is used in Example 2.)
1. | Select the Items property of the list box. |
2. | Click on the ellipsis button on the right side of the Settings box. (A window titled String Collection Editor will be displayed.) |
3. | Type in the first item, and press Enter. |
4. | Repeat Step 3 for each of the other items. |
5. | When you are finished entering items, click on the OK button. |
A combo box is best thought of as a text box with a helping list box attached. With an ordinary text box, the user must type information into the box. With a combo box, the user has the option of either typing in information or just selecting the appropriate piece of information from a list. The information is then displayed at the top of the combo box. The three types of combo box, called Simple, DropDown, and DropDownList, are specified by the DropDownStyle property. See Figure 9.1 DropDown combo boxes are used in Windows applications as text boxes with a "history list" (list of past entries) from which you can either type a new entry or select an old entry. The standard prefix for the name of a combo box is cbo.
With a Simple combo box, the list is always visible. With a DropDown combo box, the list drops down when the user clicks on the arrow and then disappears after a selection is made. In either case, when an item from the list is highlighted, the item automatically appears in the text box at the top and its value is assigned to the Text property of the combo box. The DropDownList combo box looks like the DropDown combo box; the difference is that the user can only select an item from the list and cannot type into the text box.
Combo boxes have essentially the same properties, events, and methods as list boxes. In particular, all the statements discussed for list boxes also hold for combo boxes. The Text property determines what appears at the top of the combo box before the user accesses the combo box. The DropDownStyle property of a combo box must be specified at design time.
The following program uses a Simple combo box to obtain a person's title for the first line of the address of a letter. Note: At design time, first set the combo box's DropDownStyle property to Simple, and then lengthen the height of the combo box.
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click txtDisplay.Text = cboTitle.Text & " " & txtName.Text End Sub [Run, select an item from the combo box, type a name into the Name text box, and click the button.]
The same program with a style DropDown or DropDownList combo box produces the output shown below.
|
Windows applications, such as Word, Excel, and Notepad, all provide the same standard Open dialog box to help you specify the file you want to open. Figure 9.2 shows an Open dialog box that could be used with Notepad to open a text file. The same Open dialog box, with all its functionality, is available to Visual Basic programs courtesy of the OpenFileDialog control.
The OpenFileDialog control is in the Dialogs section of the Toolbox. When you place the control on a form it will not be visible. The icon and the default name, OpenFileDialog1, appear in the pane below the Main area. (We will not change the name since the default name completely describes the control's function.) The only property we will set for the control is the Filter property, which determines what text appears in the "Files of type:" combo box and what types of files will be displayed in the Main region of the dialog box. The simplest setting has the form
text for combo box|*.ext
where ext is a two- or three-letter extension describing the types of files to display. For our purposes, the most used setting for the Filter property will be
Text Documents (*.TXT)|*.TXT
The statement
OpenFileDialog1.ShowDialog()
brings the Open dialog box into play. After a file has been selected and the Open button pressed, the value of
OpenFileDialog1.FileName
will be the file's filespec; including drive, path, file name, and extension.
The following program displays the contents of a text file selected by the user with an Open dialog box:
Private Sub btnSelect_Click(...) Handles btnSelect.Click Dim textFile As String OpenFileDialog1.ShowDialog() 'Open dialog box appears and program 'pauses until a selection is made textFile = OpenFileDialog1.FileName Dim sr As IO.StreamReader = IO.File.OpenText(textFile) lstOutput.Items.Clear() Do While sr.Peek <> -1 lstOutput.Items.Add(sr.ReadLine) Loop sr.Close() End Sub [Run, and press the button. (Assume that the user makes choices leading to the situation in Figure 9.2) Select the file USPRES.TXT, and click on the Open button in the dialog box.]
|
1. | Write code to copy the contents of a list box into a file. |
2. | Give a statement that will display the last item in the combo box cboBox. |
For Exercises 1 through 16, suppose that the list box lstBox is as shown and determine the effect of the code. (Assume that the Sorted property is set to True.)
1. | txtOutput.Text = lstBox.Text |
2. | lstBox.Text = CStr(lstBox.Items(2)) |
3. | txtOutput.Text = CStr(lstBox.Items(lstBox.Items.Count - 1)) |
4. | txtOutput.Text = CStr(lstBox.Item(lstBox.SelectedIndex)) |
5. | txtOutput.Text = CStr(lstBox.SelectedIndex) |
6. | lstBox.Items.Add(lstBox.Text) |
7. | lstBox.Items.Add("Haydn") |
8. | lstBox.Items.Remove("Chopin") |
9. | lstBox.Items.RemoveAt(0) |
10. | lstBox.Items.RemoveAt(lstBox.SelectedIndex) |
11. | lstBox.Items.RemoveAt(lstBox.Items.Count 1) |
12. | lstBox.Items.Clear() |
13. | Dim total As Integer = 0 For n As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(n)).Length = 6 Then total += 1 End If Next txtOutput.Text = CStr(total) |
14. | Dim sw As IO.StreamWriter = IO.File.CreateText("COMPOSERS.TXT") For n As Integer = 0 To lstBox.Items.Count - 1 sw.WriteLine(lstBox.Items(n)) Next sw.Close() |
15. | Dim composer(10) As String For n As Integer = 0 To lstBox.Items.Count - 1 composer(n) = CStr(lstBox.Items(n)) 'Composer() is a string array Next |
16. | Dim composer(100) As String Dim highestIndex As Integer = lstBox.Items.Count - 1 For n As Integer = 0 To highestIndex composer(n) = CStr(lstBox.Items(n)) 'Composer() is a string array Next lstBox.Items.Clear() lstBox.Sorted = False For n As Integer = highestIndex To 0 Step -1 lstBox.Items.Add(composer(n)) Next |
In Exercises 17 through 26, assume that the Simple combo box cboBox appears as shown and that the Sorted property is set to True. Give a statement or statements that will carry out the stated task.
17. | Highlight the name Dante. |
18. | Highlight the third item of the list. (The statement should do the job even if additional items were added to the list.) |
19. | Delete the name Shakespeare. |
20. | Delete the name Goethe. |
21. | Delete the last name in the list. (The statement should do the job even if additional items were added to the list.) |
22. | Insert the name Cervantes. Where will it be inserted? |
23. | Display every other item of the list in another list box. |
24. | Delete every item beginning with the letter M. (The code should do the job even if additional items were added to the list.) |
25. | Determine if Cervantes is in the list. (The statement should do the job even if additional items were added to the list.) |
26. | Store the items in the file AUTHORS.TXT. |
In Exercises 27 through 32, suppose that the form has a list box containing positive single-digit numbers, a button, and a text box. Write a Click event procedure for the button that displays the requested information in the text box or another list box.
27. | The average of the numbers in the list box. |
28. | The largest number in the list box. |
29. | Every other number in the list box. |
30. | All numbers greater than the average. |
31. | The spread of the list, that is, the difference between the largest and smallest numbers in the list box. |
32. | The median of the numbers in the list. (The median of a set of n numbers is a number such that half the n numbers fall below the median, and half fall above. If the number of numbers n is odd, the median is the middle number when the numbers are arranged in ascending order. If the number of numbers n is even, the median is the average of the two middle numbers when the numbers are arranged in ascending order.) |
33. | The file POPULAR_NAMES.TXT contains the 20 most popular names given to newborns in the year 2000. Use a list box to sort the names into alphabetical order, and then place the alphabetized list into a new ordered file. |
34. | Write a program that contains a list box (with Sorted = False ), a label, and two buttons captioned "Add an Item" and "Delete an Item". When the Add an Item button is clicked, the program should request an item with an input dialog box and then insert the item above the currently highlighted item. When the Delete an Item button is clicked, the program should remove the highlighted item from the list. At all times, the label should display the number of items in the list. |
35. | Consider the Length Converter in Figure 9.3 Write a program to place the items in the list and carry out the conversion. (See the first programming project in Chapter 7 for a table of equivalent lengths.) Figure 9.3. Form for Exercise 35.
|
36. | Write a program to ask a person which Monopoly® space he or she has landed on and then display the result in a text box. The response should be obtained with a combo box listing the squares most commonly landed on: Park Place, Illinois Avenue, Go, B&O Railroad, and Free Parking. (One possible outcome to be displayed in the text box is "You have landed on Park Place.") |
37. | Write a program to question a person about his or her IBM-compatible computer and then display a descriptive sentence in a text box. The form should contain combo boxes for brand, amount of memory, and size of screen. The lists should contain the most common responses for each category. The most common PCs are Compaq, Dell, Hewlett Packard, IBM, and Gateway 2000. The most common amounts of memory are 128MB, 256MB, 512MB, and 1GB. The most common screen sizes are 15 inches, 17 inches, and 21 inches. (One possible outcome to be displayed in the text box is "You have a Gateway 2000 computer with 256MB of memory and a 17-inch monitor.") |
1. | Sub SaveListBox() Dim sw As IO.StreamWriter = IO.File.CreateText("LISTDATA.TXT") For i As Integer = 0 to lstBox.Items.Count - 1 sw.WriteLine(lstBox.Items(i)) Next sw.Close() End Sub |
2. | txtBox.Text = CStr(cboBox.Items(cboBox.Items.Count - 1)) |