Export (0) Print
Expand All
Around the World with Visual Basic
Asynchronous Method Execution Using Delegates
Building a Progress Bar that Doesn't Progress
Calling All Operators
Create a Graphical Editor Using RichTextBox and GDI+
Creating A Breadcrumb Control
Creating a Five-Star Rating Control
Creating and Managing Secondary Threads
Data Binding Radio Buttons to a List
Deploying Assemblies
Designing With Custom Attributes
Digital Grandma
Doing Async the Easy Way
Extracting Data from .NET Assemblies
Implementing Callbacks with a Multicast Delegate
Naming and Building Assemblies in Visual Basic .NET
Programming Events of the Framework Class Libraries
Programming I/O with Streams in Visual Basic .NET
Reflection in Visual Basic .NET
Remembering User Information in Visual Basic .NET
Advanced Basics: Revisiting Operator Overloading
Scaling Up: The Very Busy Background Compiler
Synchronizing Multiple Windows Forms
Thread Synchronization
Updating the UI from a Secondary Thread
Using Inheritance in the .NET World
Using the ReaderWriterLock Class
Visual Basic: Simplify Common Tasks by Customizing the My Namespace
What's My IP Address?
Windows Forms Controls: Z-order and Copying Collections
Expand Minimize

Variables and Constants for Visual Basic .NET Beginners

Visual Studio .NET 2003

Betsy Aoki
Microsoft Corporation

March 2005

Summary: In this, the second part of Betsy's exploration of Visual Basic .NET for new programmers, she looks at variables and constants and how you can use them in your programs. (9 printed pages)

Download the MSDNVars.msi file.


Constants and Variables
Using Variables, Integers, and Strings


Perhaps one of the more astounding, confounding, and amusing things about Visual Basic .NET programs is the way they resemble sophisticated waterworks—each tiny bucket passing values to other tiny buckets until waterwheels are spinning like mad.

You think you safely left the old X and Y variables behind you in grade school, and here they are cheerfully popping up again under new and assumed names. They have come back with names that bring terror to the heart of English majors, names of power and might that say nothing to the novice but everything to the initiated, burly names like intQuantity and strHomePhone.

These names force upon you certain realizations. You realize these names are a mystery—in part because they are the devil to pronounce in polite conversations. Also, you realize belatedly that if you are going to program something, apparently math is involved.

Take heart. This article will assist you in puzzling out the building blocks of your Visual Basic .NET code and demystifying the math part. While mathematics is the engine that makes computer programs run, the math does not have to be complicated in order to make your programs powerful.

Constants and Variables

First, it's good to get used to the idea of constants and variables again. Going back to our waterworks analogy, let's suppose that some wise guy decides he's going to fill up some of the waterworks buckets with quick-drying cement when you are not looking. Not all of them in your waterworks, just some of them.

Now, thanks to this prankster, you have heavier buckets, but you also have certainty—when you look inside the cement-filled buckets, you see nothing but cement. The other buckets in your waterworks can be filled to varying degrees, but not the cement-filled buckets. They always return the value of heavy cement. These cement-filled buckets are like constants in Visual Basic. NET. Once they are set up, they are not supposed to change for the life of your program. The more flexible buckets in this metaphor act like variables—their water levels, by their virtue of them starting out empty, can change as your Visual Basic .NET program demands.

Before you can use variables or constants in Visual Basic .NET, you are required to declare them. Think of it like going through customs when traveling to another country. At the customs office, you have to state what you have in your luggage and how much it is worth. In this case, you have to state what kinds of things the program will be working with and how much memory they will take up.

Declaring constants and variables is done in the following format:

Const ConstantName as   DataType 
Dim  Variable Name As   DataType 

Visual Basic .NET has many data types to choose from, but we'll start with the basics—integer, decimal, and string.

An integer is a number without a decimal point (Example: 1, 35, 0, -1). A decimal uses the decimal point (1.45, 305.9). A string is a character or characters that won't be used in calculations ("Betsy", "206-555-5555", "123 Sesame Street"), but that you will need for other purposes. When doing things like business or financial transactions, you are likely to use decimals. When recording or looking up customer information, like addresses or favorite color, you will be using strings. Integers are good for counting and keeping track of what's happening in the program (something we will cover later) as well as calculations where fractions don't come into the picture.

Real examples of declarations might look like the following:

Dim strHomePhone As String
Dim decSaleDiscount As Decimal

See the three-letter prefix? ("str" "dec")? It's considered good programming manners to say what kind of data type the constant or variable is by including that designation inside its name, or identifier. This naming convention also helps you keep track of what you can and can't do with that item as you create your code. For the officially recommended naming conventions, see http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconNamingGuidelines.asp.

Declaring the data type (as String, as Decimal, as Integer, and so on) lets Visual Basic .NET know how to handle that item in memory, but also what kinds of things that item can be expected to do. You can't do math on a phone number in a string, and you can't expect Shakespeare from a decimal.

Using Variables, Integers, and Strings

All right you say, enough of the throat clearing, what can I DO with these things? I've opened up a new Visual Basic project, and picked Windows application. I've got my Windows form open in design mode, I've just dragged Button1 over on top of it from the Toolbox, and I want to make this button do something. This current state of my form is shown in Figure 1 below.

Figure 1. Making a Button do something

We'll leave its name as Button1 for now, but in a real program you would probably choose to rename your buttons and labels to the Visual Basic naming conventions that communicate their functions more clearly: btnSubmit, btnExit, lblMaryNewAge.

Right-click on the button and set the text property of Button1 to Show Mary's Age(s), as shown in Figure 2.

Figure 2. Properties for the Button

Double-click on your button to get the code view of the situation (Figure 3). Note how your cursor lands smack-dab in the middle of the place it needs to be to make that button do something once an unsuspecting user clicks on it.

Figure 3. Code for the Button

Private Sub is not, despite what you might think, a sandwich that you don't have to share with your coworkers, or your personal vehicle for a voyage under the sea. Private Sub is the notation for a private sub procedure.

Private means that what goes on inside Private Sub until End Sub will not apply to the rest of the program. So, if you name a variable MyDog and set the value of that variable to the string Spot", only inside that sub procedure will the dog be Spot. If the user clicks another button, the variable for the dog name could begin at Rover.

Type in the following code such that the whole sub procedure looks like this

  Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim intMaryAge As Integer
        Dim strMaryName As String

        intMaryAge = 7
        strMaryName = "Mary"
        MessageBox.Show("Hi, my name is " & strMaryName & _
          " and my age is " & intMaryAge)

    End Sub

When you click on the blue arrow to run the program, you should see a message window pop-up that looks like Figure 4.

Figure 4. Message box

If you didn't type spaces exactly as in the example, the message words may be squashed or look odd. Adjust what's inside the quotation marks until the message box text looks normal.

To quit the program you just made, click on the blue square as shown in Figure 5.

Figure 5. Stopping the running program

Now for the purposes of this example, because the program is only displaying Mary's age and not doing any math, we could have gotten away with making it strMaryAge rather than intMaryAge and declaring that as a string instead of an integer. But in the next example, we are going to do something to show the difference between integers and strings.

  1. Click on Design view.
  2. Add another Label to your form (Label1).
  3. Add a text box (TextBox1), with the text property in both the label and the text box to be nothing. You do this by right-clicking on the label and the properties window should show up on the right pane. Scroll down to where you can see the Text property and edit it to be blank. Do the same for Label1. An example of these setting is shown in Figure 6.

    Figure 6. Properties for the TextBox

  4. Go back to Design view and add another button to your form (Button2).
  5. Make the Text property of Button2 say Exit.
  6. Double Click on Button2 and type in these words inside the Private Sub:

    Now, go to the Private Sub for Button1, or, if you want to be sure, go back to Design view and double-click on Button1. You should see all the stuff we typed about Mary.

    Make it look like this:

      Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
            Dim intMaryAge As Integer
            Dim strMaryName As String
            Dim intNewAge As Integer
            intMaryAge = 7
            strMaryName = "Mary"
            MessageBox.Show("Hi, my name is " & strMaryName & _
              " and my age is " & intMaryAge)
            intNewAge = CInt(TextBox1.Text)
            intMaryAge = intMaryAge + intNewAge
            Label1.Text = "Mary's new age is " & intMaryAge
        End Sub

    Type a number into TextBox1. Try to run the program (blue arrow), and if something goes wrong, click the Exit button (Button2, the one you made work by using Me.Close ()).

You should see the original message box show up and claim Mary's age is 7 (at that point in the program, the variable intMaryAge has been assigned a value of 7). But in Label1, where the math results are shown, intMaryAge has been changed to reflect the addition of whatever value you typed into the Text box.

You've converted the value inside the Text property of TextBox1 to an Integer CInt is a function already built into Visual Basic that will do this for you. This conversion ensures that the sub procedure treats any numbers typed into the text box as numbers and not strings. By the end of the sub procedure, you've displayed intMaryAge as its new value in Label1. If you want a shorter way to write out your addition statement, you can write intMaryAge += intNewAge and you get the same thing as intMaryAge = intMaryAge + intNewAge.

This program also sneaks in a few of the already-made elements of a Windows form that you will find useful in other places. For example, getting a Message Box to show up for the user, putting words into the Message Box, handling input from a Text Box, and getting information to show up on a Label. All this code is very straightforward, and meant to be so to allow you to get a handle on what changes went through your code.


Well, now you've done it. You've written a program that does absolutely nothing, except show you different things based on different constants and variables within your program. You've also allowed Mary to be both younger and older at the same time, which I suspect, is true of all of us.

Betsy Aoki is a community PM for Microsoft. Her gentle neuroses are avidly expressed in her e-mails, blog posts, and Visual Basic .NET.

© 2015 Microsoft