
- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary

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 |