
Beginning Visual Basic 2005 (2006)
.pdf
Chapter 5
How It Works
The pair of braces {} allows you to set the values that should be held in an array directly. In this instance, you have five values to enter into the array, separated with commas. Notice that when you do this, you don’t specify an upper bound for the array; instead, you use empty parentheses. Visual Basic 2005 prefers to calculate the upper bound for you based on the values you supply.
‘Declare and populate an array
Dim strMyFriends() As String = {“Robbin”, “Bryan”, “Stephanie”, _ “Sydney”, “Katie”}
This technique can be quite awkward to use when populating large arrays. If your program relies on populating large arrays, you might want to use the method illustrated earlier: specifying the positions and the values.
Understanding Enumerations
So far, the variables you’ve seen had virtually no limitations on the kinds of data you can store in them. Technical limits notwithstanding, if you have a variable defined As Integer, you can put any number you like in it. The same holds true for String and Double. You have seen another variable type, however, that has only two possible values: Boolean variables can be either True or False and nothing else.
Often, when writing code, you want to limit the possible values that can be stored in a variable. For example, if you have a variable that stores the number of doors that a car has, do you really want to be able to store the value 163,234?
Using Enumerations
Enumerations allow you to build a new type of variable, based on one of these data types: Integer, Long, Short, or Byte. This variable can be set to one value of a set of possible values that you define, and ideally prevent someone from supplying invalid values. It is used to provide clarity in the code, as it can describe a particular value. In the following Try It Out, you’ll look at how to build an application that looks at the time of day and, based on that, can record a DayAction of one of these possible values:
Asleep
Getting ready for work
Traveling to work
At work
At lunch
Traveling from work
Relaxing with friends
Getting ready for bed
136

Working with Data Structures
Try It Out |
Using Enumerations |
1.Using Visual Studio 2005, create a new Windows Application project called Enum Demo.
2.Enumerations are typically defined as a member of the class that intends to use them (though this does not have to be the case). When the Designer for Form1 opens, open the Code Editor for the form and add the highlighted code to the top:
Public Class Form1
‘DayAction Enumeration
Private Enum DayAction As Integer
Asleep = 0
GettingReadyForWork = 1
TravelingToWork = 2
AtWork = 3
AtLunch = 4
TravelingFromWork = 5
RelaxingWithFriends = 6
GettingReadyForBed = 7
End Enum
3.With an enumeration defined, you can create new member variables that use the enumeration as their data type. Add this member:
‘Declare variable
Private CurrentState As DayAction
4.Flip back to the Designer for Form1. Change the Text property of Form1 to What’s Matt Doing?.
5.Now add a DateTimePicker control and set the following properties.
Set Name to dtpHour.
Set Format to Time.
Set ShowUpDown to True.
Set Value to 00:00 AM.
Set Size to 91, 20.
6.Add a Label control to the form, set its Name property to lblState, and set its Text property to State Not Initialized. Resize your form so it looks similar to Figure 5-6.
Figure 5-6
137

Chapter 5
7.Double-click the background of the form to create a new Load event handler. Add the following highlighted code. You’ll receive an error message that Hour is not defined; you can ignore this error, because in the next step you’ll be defining Hour as a new property of the form:
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
‘Set the Hour property to the current hour
Me.Hour = Now.Hour
End Sub
8.Now, add following code below the code you added in step 3 in the Code Editor for the form:
‘Hour property
Private Property Hour() As Integer Get
‘Return the current hour displayed Return dtpHour.Value.Hour
End Get
Set(ByVal value As Integer)
‘Set the date using the hour passed to this property dtpHour.Value = _
New Date(Now.Year, Now.Month, Now.Day, value, 0, 0) ‘Set the display text
lblState.Text = “At “ & value & “:00, Matt is “ End Set
End Property
9.In the Class Name combo box at the top of the Code Editor, select dtpHour, and in the Method Name combo box, select the ValueChanged event. Add the following highlighted code to the event handler:
Private Sub dtpHour_ValueChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles dtpHour.ValueChanged
‘Update the Hour property
Me.Hour = dtpHour.Value.Hour
End Sub
10.Run the project. You will be able to click the up and down arrows in the date and time picker control and see the text updated to reflect the hour selected as shown in Figure 5-7.
Figure 5-7
138

Working with Data Structures
How It Works
In this application, the user will be able to use the date-time picker to choose the hour. You then look at the hour and determine which one of the eight states Matt is in at the given time. To achieve this, you have to keep the hour around somehow. To store the hour, you have created a property for the form in addition to the properties it already has, such as Name. The new property is called Hour, and it is used to set the current hour in the DateTimePicker control and the label control. The property is defined with a Property . . . End Property statement:
Private Property Hour() As Integer Get
. . .
Return dtpHour.Value.Hour End Get
Set(ByVal value As Integer)
. . .
End Set End Property
Notice the Get . . . End Get and Set . . . End Set blocks inside the Property . . . End Property statement. The Get block contains a Return statement and is called automatically to return the property value when the property name appears in an expression. The data type to be returned is not specified in the Get statement, because it was already declared As Integer in the Property statement. The Set block is called automatically when the value is set, such as by putting the property name to the left of an equals sign.
When the application starts, you set the Hour property to the current hour on your computer. You get this information from Now, a Date variable containing the current date and time:
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
‘Set the Hour property to the current hour Me.Hour = Now.Hour
End Sub
You also set the Hour property when the Value property changes in the DateTimePicker control:
Private Sub dtpHour_ValueChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles dtpHour.ValueChanged
‘Update the Hour property Me.Hour = dtpHour.Value.Hour
End Sub
When the Hour property is set, you have to update the value of the DateTimePicker control to show the new hour value, and you have to update the label on the form as well. The code to perform these actions is put inside the Set block for the Hour property.
The first update that you perform is to update the Value property of the DateTimePicker control. The Value property of the date-time picker is a Date data type; thus, you cannot simply set the hour in this control, although you can retrieve just the hour from this property. In order to update this property, you must pass it a Date data type.
139

Chapter 5
You do this by calling New (see Chapter 10) for the Date class, passing it the different date and time parts as shown in the code: year, month, day, hour, minute, second. You get the year, month, and day by extracting them from Now variable. The hour is passed using the value that was passed to this Hour property, and the minutes and seconds are passed as 0, since you do not want to update the specific minutes or seconds.
‘Set the date using the hour passed to this property dtpHour.Value = _
New Date(Now.Year, Now.Month, Now.Day, value, 0, 0)
The second update performed by this Hour property is to update the label on the form using some static text and the hour that is being set in this property.
‘Set the display text
lblState.Text = “At “ & value & “:00, Matt is “
You have not evaluated the Hour property to determine the state, but you will do that next:
Determining the State
In the next Try It Out, you look at determining the state when the Hour property is set. You can take the hour returned by the DateTimePicker control and use it to determine which value in your enumeration it matches. This section demonstrates this and displays the value on your form.
Try It Out |
Determining State |
1.Open the Code Editor for Form1 and modify the Hour property as follows:
Set(ByVal value As Integer)
‘Set the date using the hour passed to this property dtpHour.Value = _
New Date(Now.Year, Now.Month, Now.Day, value, 0, 0)
‘Determine the state
If value >= 6 And value < 7 Then CurrentState = DayAction.TravelingToWork
ElseIf value >= 7 And value < 8 Then CurrentState = DayAction.TravelingToWork
ElseIf value >= 8 And value < 13 Then CurrentState = DayAction.AtWork ElseIf value >= 13 And value < 14 Then CurrentState = DayAction.AtLunch
ElseIf value >= 14 And value < 17 Then
CurrentState = DayAction.AtWork
ElseIf value >= 17 And value < 18 Then
CurrentState = DayAction.TravelingFromWork
ElseIf value >= 18 And value < 22 Then
CurrentState = DayAction.RelaxingWithFriends
ElseIf value >= 22 And value < 23 Then
CurrentState = DayAction.GettingReadyForBed
Else
140

Working with Data Structures
CurrentState = DayAction.Asleep
End If
‘Set the display text
lblState.Text = “At “ & value & “:00, Matt is “ & CurrentState End Set
2.Run the project. You’ll see something like Figure 5-8.
Figure 5-8
3.Here’s the problem: The user doesn’t know what 3 means. Close the project and find the following section of code at the end of the Hour property:
‘Set the display text
lblState.Text = “At “ & value & “:00, Matt is “ & CurrentState
4.Change the last line to read as follows:
‘Set the display text
lblState.Text = “At “ & value & “:00, Matt is “ & CurrentState.ToString
5.Now run the project and you’ll see something like Figure 5-9.
Figure 5-9
How It Works
As you typed the code, you might have noticed that whenever you tried to set a value against CurrentState, you were presented with an enumerated list of possibilities as shown in Figure 5-10.
Visual Studio 2005 knows that CurrentState is of type DayAction. It also knows that DayAction is an enumeration and that it defines eight possible values, each of which is displayed in the IntelliSense popup box. Clicking an item in the enumerated list causes a ToolTip to be displayed with the actual value of the item; for example, clicking DayAction.RelaxingWithFriends will display a ToolTip with a value of 6.
141

Chapter 5
Figure 5-10
Fundamentally though, because DayAction is based on an integer, CurrentState is an integer value. That’s why, the first time you ran the project with the state determination code in place, you saw an integer at the end of the status string. At 10 A.M., you know that Matt is at work, or rather CurrentState equals DayAction.AtWork. You defined this as 3, which is why 3 is displayed at the end of the string.
What you’ve done in this Try It Out is to tack a call to the ToString method onto the end of the CurrentState variable. This results in a string representation of DayAction being used, rather than the integer representation.
Enumerations are incredibly useful when you want to store one of a possible set of values in a variable. As you start to drill into more complex objects in the Framework, you’ll find that they are used all over the place!
Setting Invalid Values
One of the limitations of enumerations is that it is possible to store a value that technically isn’t one of the possible defined values of the enumeration. For example, if you change the Hour property so that rather than setting CurrentState to Asleep, you can set it to 999:
ElseIf value >= 22 And value < 23 Then
CurrentState = DayAction.GettingReadyForBed
Else
CurrentState = 999
End If
If you build the project, you’ll notice that Visual Basic 2005 doesn’t flag this as an error. Further, if you actually run the project, you’ll see that the value for CurrentState is shown in the text box as 999.
So, you can see that you can set a variable that references an enumeration to a value that is not defined in that enumeration and the application will still “work” (as long as the value is of the same type as the enumeration). If you build classes that use enumerations, you have to rely on the consumer of that class being well behaved. One technique to solve this problem would be to disallow invalid values in any properties that used the enumeration as their data type.
142

Working with Data Structures
Understanding Constants
Another good programming practice that you need to look at is the constant. Imagine you have these two methods, each of which does something with a given file on the computer’s disk. (Obviously, we’re omitting the code here that actually manipulates the file.)
Public Sub DoSomething() ‘What’s the filename?
Dim strFileName As String = “c:\Temp\Demo.txt” ‘Open the file
. . .
End Sub
Public Sub DoSomethingElse() ‘What’s the filename?
Dim strFileName As String = “c:\Temp\Demo.txt” ‘Do something with the file
. . .
End Sub
Using Constants
The code defining a string literal gives the name of a file twice. This is poor programming practice because if both methods are supposed to access the same file, and if that filename changes, this change has to be made in two separate places.
In this instance, both methods are next to each other and the program itself is small, but imagine that you have a massive program in which a separate string literal pointing to the file is defined in 10, 50, or even 1,000 places. If you need to change the filename, you’ll have to change it many times. This is exactly the kind of thing that leads to serious problems for maintaining software code.
What you need to do instead is define the filename globally and then use that global symbol for the filename in the code, rather than using a string literal. This is what a constant is. It is, in effect, a special kind of “variable” that cannot actually be varied when the program is running. In the next Try It Out, you learn to use constants.
Try It Out |
Using Constants |
1.Using Visual Studio 2005, create a new Windows Application project and call it Constants Demo.
2.When the Designer for Form1 opens, add three buttons. Set the Name property of the first button to btnOne, the second to btnTwo, and the third to btnThree. Change the Text property of each to One, Two, and Three, respectively. Your form should look like Figure 5-11.
Figure 5-11
143

Chapter 5
3.View the Code Editor and at the top of the class definition, add the highlighted code:
Public Class Form1
‘File name constant
Private Const strFileName As String = “C:\Temp\Hello.txt”
4.In the Class Name combo box at the top of the editor, select btnOne, and in the Method Name combo box select the Click event. Add the following highlighted code to the Click event handler:
Private Sub btnOne_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnOne.Click
‘Using a constant
MessageBox.Show(“1: “ & strFileName, “Constants Demo”)
End Sub
5.Now select btnTwo in the Class Name combo box and select its Click event in the Method Name combo box. Add the highlighted code:
Private Sub btnTwo_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnTwo.Click
‘Using the constant again
MessageBox.Show(“2: “ & strFileName, “Constants Demo”)
End Sub
6.Finally, select btnThree in the Class Name combo box and the Click event in the Method Name combo box. Add this code to the Click event handler:
Private Sub btnThree_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnThree.Click
‘Reusing the constant one more time
MessageBox.Show(“3: “ & strFileName, “Constants Demo”)
End Sub
7.Now run the project and click button One. You’ll see the message box shown in Figure 5-12.
Figure 5-12
Likewise, you’ll see the same filename if you click buttons Two or Three.
144

Working with Data Structures
How It Works
A constant is actually a type of value that cannot be changed when the program is running. It is defined as a variable is, but you add Const to the definition.
‘File name constant
Private Const strFileName As String = “C:\Temp\Hello.txt”
You’ll notice that it has a data type, just like a variable, and you have to give it a value when it’s defined
— which makes sense, because you can’t change it later.
When you want to use the constant, you refer to it just as you would refer to any variable:
Private Sub btnOne_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnOne.Click
‘Using a constant
MessageBox.Show(“1: “ & strFileName, “Constants Demo”) End Sub
As mentioned before, the appeal of a constant is that it allows you to change a value that’s used throughout a piece of code by altering a single piece of code. However, be aware that you can change constants only at design time; you cannot change their values at run time. Look at how this works.
Different Constant Types
In this section, you’ve seen how to use a string constant, but you can use other types of variables as constants. There are some rules: Basically, a constant must not be able to change, so you should not store an object data type (which we will discuss in Chapter 10) in a constant.
Integers are very common types of constants. They can be defined like this:
Public Const intHoursAsleepPerDay As Integer = 8
Also, it’s fairly common to see constants used with enumerations, like this:
Public Const intMattsTypicalState As DayAction = DayAction.AtWork
Str uctures
Applications very commonly need to store several pieces of information of different data types that all relate to one thing and must be kept together in a group, such as a customer’s name and address (strings) and balance (a number). Usually, an object of a class is used to hold such a group of variables, as you’ll discover in Chapter 10, but you can also use a structure. Structures are similar to class objects but are somewhat simpler, so they’re discussed here.
145