Tải bản đầy đủ - 0 (trang)
3 ListBox, ComboBox, and CheckedListBox

3 ListBox, ComboBox, and CheckedListBox

Tải bản đầy đủ - 0trang

2.3 ListBox, ComboBox, and CheckedListBox

Selecting Multiple Items

The SelectionMode property of a ListBox can be configured to allow the user to make multiple selections. You can set it to each of the following:

None—no items can be selected.

One—only a single item can be selected.

MultiSimple—multiple individual items can be selected by clicking the mouse on each item.

MultiExtended—multiple individual items can be selected by holding down the Ctrl

key, and a range of items can be selected by holding down the Shift key.

If a ListBox or CheckedListBox control allows multiple selections, the SelectedIndices property contains a collection of the indexes of the selected items. The following example loops

through SelectedIndices:

For Each index As Integer in lstNames.SelectedIndices


Similarly, the SelectedItems property is a collection containing all currently selected ListBox


For Each item As String in lstNames.SelectedItems


The CheckedListBox control also has a CheckedItems property that is a collection containing all items checked by the user.

For Each item As String in lstNames.CheckedItems



To insert an array into a list-type control, pass the array to the Items.AddRange method. For

example, the following statement declares an array of strings named colors and adds it to a

list box:

Dim colors() As String = {''Red'',''Blue'',''Green''}


The same technique works with ComboBox and CheckedListBox controls.

Adding and Inserting Single Items

To append an item to the end of the Items collection in a list-type control, call the Items.Add

method. For example:


To insert an item into the beginning or middle of a list-type control, call its Items.Insert

method. Pass the index position where you want to insert. This is the general format:

ControlName.Items.Insert(index, item)

ControlName is the name of the control. For example, the following inserts “Yellow” into

index 0 (at the beginning):

lstColors.Items.Insert(0, ''Yellow'')

Removing Items

The Items.Remove and Items.RemoveAt methods both erase one item from a list-type control. This is the general format for both methods:





Chapter 2

Input Validation and User Interfaces

ControlName is the name of the control. Item is an object that exactly matches one of the

items in the Items collection. Index is the index position where you wish to remove an

item. For example, the following statement removes the color “Yellow” from the lstColors list box:


The following statement removes the item at index position 2:


If you pass an item to the Remove method that is not in the Items collection, nothing is

removed. If you pass an index to the RemoveAt method that is out of range, an exception is


The Items.Clear method removes all items from the collection.

Inserting Objects into List-Type Controls

As we have shown, it is easy to insert an array into a list-type control. However, applications

often use parallel arrays with related information. For example, you might have an array of

drink names as strings that parallels an array of prices for those drinks. How could you

insert both into a ListBox?

You can create a class that defines the objects to be inserted in the list. The class must have

properties to hold the data, as well as a ToString method. For example, DrinkType is a class

that contains the name and price of a drink:

Class DrinkType

Public Name As String

Public Price As Double

Public Overrides Function ToString() As String

Return Name

End Function

End Class

DrinkType must contain a ToString method, which is called by the ListBox control when displaying the drink names.

To demonstrate, imagine a simple application that displays a list box containing the

names of drinks. When the user selects a drink, the price of the drink appears. In Figure 2-14, the user interface shows how the price changes when the user selects different


First, let’s define a couple of arrays of drink names and their corresponding prices:

Private ReadOnly Names() As String = {''Espresso'', ''Cappucino'',

''Latte'', ''Cortadito'', ''Cafe au Lait'', ''Chai Tea''}

Private ReadOnly Prices() As Double = {2.0, 3.5, 3.4, 1.5, 2.2, 1.5}

We certainly could have inserted only the drink names into a ListBox, and used its

SelectedIndex to reference data in other parallel arrays. Let us consider, however, the

advantages of using the DrinkType class. First, DrinkType objects can be passed easily as

parameters between methods. Second, parallel arrays often become unsynchronized

when new values are added or removed. We will not have that problem with an array or

collection of DrinkType objects. Finally, DrinkType objects can easily be inserted into a

database table.

Next, let’s define an array named drinks that holds DrinkType objects:

Private drinks(5) As DrinkType

2.3 ListBox, ComboBox, and CheckedListBox

Figure 2-14 Displaying a list of drinks and prices

Next, the Form_Load event handler loops through the Names and Prices arrays and assigns

their values to the objects in the drinks array:

1 Private Sub Form1_Load() Handles MyBase.Load


For i As Integer = 0 To Names.Count – 1


drinks(i) = New DrinkType


drinks(i).Name = Names(i)


drinks(i).Price = Prices(i)





8 End Sub

Line 3 creates a new DrinkType object and assigns it to the current array position. Lines 4–5

assign the DrinkType properties, and line 7 copies the drinks array into the list box when

the application starts.

In the SelectedIndexChanged event handler for the ListBox, we get the selected DrinkType

object and copy its price to a label:

1 Private Sub lstDrinks_SelectedIndexChanged() _


Handles lstDrinks.SelectedIndexChanged



Dim aDrink As DrinkType = CType(lstDrinks.SelectedItem, DrinkType)


lblPrice.Text = aDrink.Price.ToString(''c'')

6 End Sub

The SelectedItem property of a list box returns a plain object, so it was cast it into a DrinkType object on line 4. Then, on line 5, we were able to access the drink’s Price field.


It is safe to say that connecting an object array to a list-type control can make your program code simpler. This is because each object may contain a number of fields, allowing

you to keep all the information together. It is true that you have to invest some time in

creating a class to hold the data. But as your programs become more object-oriented, this

task will become natural, and you will find that classes make it easier to write advanced




Chapter 2

Input Validation and User Interfaces


11. What is the purpose of the CheckOnClick property in the CheckedListBox


12. Which property of a ListBox contains the indexes of all the selected items?

13. Which ListBox property controls the way multiple items are selected?

14. Which ComboBox method fills the list from an array?

15. Which ComboBox method removes the item at index position 2?


Dates and Times

Many applications use date and time information. Some do scheduling of meetings, projects,

appointments, and events. Other applications store information about events, such as when

a stock was purchased or when a home was sold. The .NET framework provides several

classes that make date and time manipulation very easy:

• DateTime

• TimeSpan

• DateTimePicker

First, we will start with the DateTimePicker control, which provides an easy-to-use interface

for collecting or displaying date and time information. Then we will show some easy techniques for doing arithmetic with dates and times.

DateTimePicker Control

The DateTimePicker control provides an attractive and intuitive way to display and ask for

date information from the user. You can use it to display either a date or a time, depending

on how it is configured. Normally, when the user clicks the dropdown arrow, a month calendar drops down, as shown in Figure 2-15.

Figure 2-15 Dropdown month calendar in the DateTimePicker control

The DateTimePicker uses very little screen space until it is activated. The Format property

controls the appearance of the date or time. Choices for the Format property are Long,

Short, Time, or Custom. If Custom is selected, another property named CustomFormat is

assigned a custom format string. Figure 2-16 shows examples of each of the standard formats, plus a custom format.

2.4 Dates and Times

Figure 2-16 Sample formats for the DateTimePicker control

Custom Date/Time Formats

Custom date/time formats are somewhat hard to remember, but you can find ample documentation by looking for Custom DateTime Format String in MSDN help. Table 2-2 shows

several sample custom format strings for displaying June 27, 2006, at 4:05 P.M.

Table 2-2 Sample date (June 27, 2006, 4:05 P.M.) displayed in custom DateTime formats

Custom Format String

Sample Display

dd MMM, yyyy

27 Jun, 2006

MM/dd/yyyy, dddd

06/27/2006, Tuesday





h:mm tt

4:05 PM

Other Properties

• The MinDateTime property limits the earliest date and time the user can select. The

MaxDateTime property limits the latest date and time the user can select. In most applications, you will set these values to prevent the user from entering unreasonable dates.

• The Value property gets or sets the date and time assigned to the control. By default,

the control displays the current date and/or time. You can set it to any value between

MinDateTime and MaxDateTime. When the user selects a new date or time, the Value

property tells you what the user selected.

• The ShowUpDown property, when set to True, prevents the dropdown month calendar from showing. Instead, the user must use the mouse to select individual parts of

the date or time. He or she can type numbers or click on spin button arrows to change

the values.

• The ShowCheckBox property determines whether to display a check box in the control.

By selecting the check box, the user can indicate that the control has been selected. Use

the Checked property set or get the value of the check box. A sample is shown here:

Date and Time Arithmetic

If you need to add a value to a DateTime object, there are couple of ways to do it. You can

add individual months, days, hours, minutes, and seconds. None of these methods modifies

the current DateTime object:






AddMonths( Integer ) As DateTime

AddDays( Double ) As DateTime

AddHours( Double ) As DateTime

AddMinutes( Double ) As DateTime

AddSeconds( Double ) As DateTime



Chapter 2

Input Validation and User Interfaces

Most of these parameters are doubles; for example, you can add 1.5 hours to a DateTime



The following adds 133 days to the current DateTime and returns a new value:

Dim later As DateTime = Today.AddDays(133)

The following adds 3.5 hours to the current DateTime and returns a new value:

later = Today.AddHours(3.5)

The following adds 60 minutes to the current DateTime and returns a new value:

later = Today.AddMinutes(60)

The following adds 30 seconds to the current DateTime and returns a new value:

later = Today.AddSeconds(30)

TimeSpan Objects

Another way to add or subtract from a DateTime is to use a TimeSpan object. You can add

and subtract TimeSpan objects from a DateTime object:

Function Add( TimeSpan ) As DateTime

Function Subtract( TimeSpan ) As DateTime

A TimeSpan object can be constructed in a number of different ways. Here are four examples:

New TimeSpan( ticks As Long )

New TimeSpan( hours As Integer, minutes As Integer,

seconds As Integer )

New TimeSpan( days As Integer, hours As Integer,

minutes As Integer, seconds As Integer )

New TimeSpan( days As Integer, hours As Integer, minutes As Integer,

seconds As Integer, milliseconds As Integer)

In the first version of the constructor, you pass the number of 100-nanosecond ticks. You are

more likely to use the second and third versions. For example, the following creates a TimeSpan

of 5 hours, 22 minutes, and 3 seconds:

Dim duration As New TimeSpan(5, 22, 3)

A TimeSpan can be added to a Date or DateTime object. Suppose an airline flight is due to

take off on April 11, 2011, at 10:30 P.M. (22:30 military time). If the duration of the flight

is 6 hours and 22 minutes, the following statements calculate the date and time of the flight’s


Dim takeoff As New DateTime(2011, 4, 11, 22, 30, 0)

Dim duration As New TimeSpan(6, 22, 0)

Dim arrival As DateTime = takeoff.Add(duration)

Therefore, the arrival time equals 4/12/2011, at 4:52 A.M., assuming that the arrival airport

is in the same time zone as the departure location.


16. Which DateTimePicker property controls whether a date or time is displayed?

17. Which DateTimePicker properties limit the earliest and latest date and time the user

can select?

2.5 ToolStrip Control

18. Which method adds N days to a DateTime object?

19. Declare a TimeSpan object named duration that equals 2 hours, 30 minutes, and

5 seconds.


ToolStrip Control

The ToolStrip control is a customizable container that holds various types of other controls.

You can use it to give your applications the look and feel of Microsoft software, such as

Windows 7 or Microsoft Office. You can use it to create custom toolbars that support

advanced layout features such as rafting, docking, and dragging by users. The ToolStrip

replaces the older ToolBar control, with many improved editing features. Most important,

you can insert buttons and other controls interactively at design time.

Adding Controls

When you add a ToolStrip control to a form, it attaches itself to the top of the form. Using

the Dock property, you can cause the strip to attach to the top, bottom, left side, or right

side of the form.

Controls placed on a ToolStrip respond to the same events they would respond to if they

were placed anywhere on a form. To create a Click handler for a ToolStripButton, for example, just double-click the control in design mode.

In design mode, a dropdown list appears when you select the ToolStrip control with the

mouse. An example is shown in Figure 2-17, with a list of available control types. You can

insert buttons, labels, separators, combo boxes, text boxes, and progress bars to a ToolStrip.

Once controls are in the ToolStrip, you can drag them to new locations with the mouse. If

the AllItemReorder property of a ToolStrip equals True, the user can press the Alt key and

drag an item from one ToolStrip to another at runtime. See an example in Figure 2-18. Each

type of control has a corresponding .NET class (see Table 2-3).

Figure 2-17 Ready to add items to a ToolStrip control

Figure 2-18 The user can press Alt and drag an item to another ToolStrip



Chapter 2

Input Validation and User Interfaces

Table 2-3 ToolStrip Control types and their corresponding classes

Control Type


















Let’s look at a few examples of ToolStrips that contain different types of controls. In

Figure 2-19, the ToolStrip contains a ComboBox. It also contains a Label that displays the

current date. To right-justify a control, set its Alignment property to Right. In Figure 2-20,

the user is selecting from a DropDownButton.

Figure 2-19 ToolStrip with ComboBox selection

Figure 2-20 Selecting from a DropDownButton

Choosing Between a MenuStrip or a DropDownButton

It can be argued that lists of actions to be carried out should be placed in menus rather than

DropDownButton controls. This is a well-accepted point of view. On the other hand, ToolStrips permit you to combine menu-like actions with lists of items, buttons, text boxes, and

other controls. By making a variety of controls available in ToolStrips, Microsoft has implicitly endorsed a flexible approach to menu and toolbar design. Also, it can be pointed out that

when lists of choices must be modified at runtime, it is much easier to change the contents of

a DropDownButton or ComboBox control than to dynamically create and delete menu items.

When you first insert a ToolStripButton into a ToolStrip, the button is configured to display

a graphic image. If you would rather have it display text only, change its DisplayStyle property to Text. If you prefer a combination of an image and text, set DisplayStyle to


To change the image displayed by the button, select the Image property. The dialog window

shown in Figure 2-21 will display. Click on the Import button to select a graphic image file

and import it into your application. If your application already has a project resource file

(containing strings, bitmaps, and so on), you can use items from it. Standard types of image

files, including BMP, GIF, JPEG, WMF, and PNG, are supported.

2.5 ToolStrip Control

Figure 2-21 Selecting a resource for a ToolStripButton’s Image property

T I P A good way to find out which images are available on your computer is to open

Windows Explorer, click the Search button, and search for Pictures and Photos.

Scaling the Button Images

Each ToolStripButton has an ImageScaling property that determines whether the button

image will be scaled (resized) to a standard image size. This property helps you create uniform button sizes in a toolbar. If you set ImageScaling to None, the button will expand to

fit the size of the image you insert. In the ToolStrip control, the ImageScalingSize property

controls the default image size for all buttons. Its default value is 16 pixels by 16 pixels,

which is the typical size of a small toolbar button.

Figure 2-22 shows the Items Collection Editor window that lets you add and edit individual ToolStrip controls. All the controls are saved in the ToolStrip’s Items property. Another

way to edit a single control is to select it with the mouse and modify values in the Properties window.

Figure 2-22 Adding items to a ToolStrip control



Chapter 2

Input Validation and User Interfaces

Design Tips

If you want to display a static list of selections that cause immediate actions, use a MenuStrip

control. If you want to select from a list of items without necessarily causing an action, use a

combo box (on the form or in a ToolStrip). In Microsoft Word, for example, ToolStrip combo

boxes are used to select fonts and paragraph styles. The DropDownButton control is perhaps

less common because it is a hybrid between a list and a button. For good examples on how

to use toolbars, look at Visual Basic Express, Visual Studio, or Microsoft Office.

It’s a good idea to assign a descriptive message to the ToolTip property of a ToolStripButton. The message appears when users hover the mouse over the control.

Each ToolStrip control should contain items relating to a single category. You can offer

options to let the user hide and display individual toolbars. Visual Studio, for example, does

this with the View | Toolbars menu command.

Tutorial 2-2:

Building the Coffee Shop application

In this tutorial, you will create a short application that lets the user purchase coffee. The

application uses a ToolStrip control with various types of buttons and lists. Here is a

simple description of the steps taken by the user to log in, purchase a drink, and log out:






The user logs in

The user selects a type of drink.

The cost of the drink, including tax, is displayed.

The user clicks the Purchase button.

The application confirms the purchase. The user can return to Step 2, or continue

on to the next step.

6. The user logs out.

The focus in this application is on the user interface, so you will use program code to

coordinate the visibility of various controls. Controls should appear only when their use

is appropriate to the application needs.

Running the Application

The following sequence helps to show how the application coordinates the visibility of

each control.

1. When the application starts up, only the Account dropdown button is visible

(Figure 2-23).

Figure 2-23 Application startup

2.5 ToolStrip Control

2. When the user selects Log in from the Account button’s menu, the login controls

on the right panel appear (Figure 2-24).

Figure 2-24 User logs in

3. When the user clicks the OK button, the login controls disappear and the Drink

Type combo box appears. In Figure 2-25, the user has selected a drink, so the price


Figure 2-25 User selected a drink type and is ready to purchase

4. In Figure 2-26, the user clicks the Purchase button, causing a confirmation dialog

to appear.

Figure 2-26 User has clicked the Purchase button

5. When the user selects Log out from the Account button list, the application

returns to its original appearance (the same screen as when it started).


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

3 ListBox, ComboBox, and CheckedListBox

Tải bản đầy đủ ngay(0 tr)