Your First Visual Basic Program

Last week we took a look at some of the standard controls that come with Visual Basic. We saw that we can change the way a control looks, by fiddling around with it’s properties.

This week, we will look at some other possibilities of controls; events. We will build a very basic program, and I’ll offer some practical tips in the process.

We will build a little calculator during this article. Fire up Visual Basic, and select ‘Standard Exe’ from the templates. You’ll notice that Visual Basic supplied some very basic and vague names for the form and the project name. (How could it not? VB doesn’t know what we will be working on). Since we want to be able to recognize the project in the future by a useful name, we’ll change the project’s name first.

In the Project Explorer Window, click on Project 1. (The uppermost-item, or ‘root-item’). In the Properties Window, you will see that ‘name’ is the only property of the project we can change. We’ll set it to ‘Calculator’ for now. As soon as you press Enter, you will notice that in the Form Designer, the new name will be reflected.

Next, we will change the Form’s name and Caption to something a little more descriptive. Click on the Form (Either in the Project Explorer, or in the Form Designer), and change it’s Caption to ‘Calculator’. We’ll set the name of the form to frmCalculator.

Hold it. Stop right there. frmCalculator? Has Peter finally managed to go mad? No. In fact, Peter’s quite stable at the very moment. This is the first tip I want to offer you.

The Hungarian Naming Convention

To improve readability in your code, and make it easier for you to look at a project some months after you last worked on it, it would be nice to have some useful names, right? If we would never ever change any names, and just use the ones that VB creates for us, in no time we would get lost. Imagine you have 5 different CommandButtons on your form. 1 for opening files, 1 for saving files, 1 as cancel, 1 for exiting the program, and 1 that makes your screen flash purple. If, in your code, you have to look at Command1 through Command5, you’ll soon be lost. However, if you supplied useful and descriptive names, your code would almost be as easy to read as plain English.

Now, to enhance readability, one of Microsoft’s programmers introduced a naming convention for programming and database objects. The basic idea behind his naming convention is to use a short abbreviation that describes the object before the name of the object as used in your program. For a form, this would be frm, for a CommandButton, it would be cmd. After the prefix, which is written completely in lower case letters, you start the actual name with a capital letter. If you have to use more than one word, you will use capitals to show you started a new word.

Looking back at the earlier example (the 5 buttons), your code would be a lot more readable if you had to look for cmdOpen, cmdSave, cmdCancel, cmdExit, and cmdFlashScreenPurple. In one glance, you would exactly know which button was being used, and it would make the understanding of a particular piece of code a lot better.

If you’re interested in a few articles with lists of widely-used prefixes, check the Microsoft Knowledge base, articles Q173738 and Q110264. This is by no means a list you want to memorize; we will see various prefixes that are commonly used in future articles anyway. One thing to keep in mind though is that you should consistently use the same prefix for the same object throughout all your code.

Back to our calculator. Your Form Designer will now look like this.

We’ll add a TextBox to the form, and 4 buttons. (This will be a very basic calculator that can add, subtract, multiply and divide only).

Set the following properties for the commands.

Leave the caption for all the controls blank. (A quick way to do this is by double clicking on ‘Caption’ in the Properties Window, and then pressing the Delete-key. (Double- clicking will automatically highlight the complete Value)). And for those wondering; Yes, I did do the above scheme in Excel. I suck at HTML-tables :). You’ll be seeing more schemes like that in future articles. Oh, and with ‘Vb-folder, I mean where ever you installed Visual Studio. (Remember, I use Visual Studio Enterprise Edition. You have to have picked ‘Graphics’ during installation. If you do NOT have the graphics, don’t set the picture property, but use the appropriate characters in the Caption property. If you want, change the font size slightly to make the character a little more visible).

Your form ought to look like this by now.

Pretty impressive, huh? Let’s save our work for now. This is where another nifty tip comes along.

Projects folder

I’d strongly recommend making a separate folder where you store your Visual Basic projects. Personally, I use a folder called ‘_Projects’ on a particular drive. The underscore makes sure it’s always the first folder to show up (Unless of course, you’d have a folder with 2 underscores). While that is nice, let’s enhance the tip somewhat. To always start in your newly defined project folder, you need to pull of a crazy little trick. (Otherwise you’ll be doing a lot of clicking; the default start-up folder for Visual Studio is the folder it got installed into. (This tip works on NT or 2000, but I’m quite sure it ought to work on other version of Windows as well).

Find the hyperlink to your VB-icon in the Start-Menu (in your profile). Right-click it.(In the newer Windows versions (NT4, SP 6+, I think), you could also just expand your Program Files folder from the Start Menu, look up VB there, and then right-click the VB-icon). Select Properties. Change the Start-In-folder to your _Projects-folder.

From now on, when you start Visual Basic, it will always offer to save projects in the new folder. I personally prefer to use sub directories for each single project. That just helps to keep things separated and visible.

Back to the calculator. We were going to save our work. Click File / Save As, and save your work somewhere. Notice you’ll be prompted both for the project (which is like the cover of a book; It keeps everything together), and the form (Which could be considered as an element (read: Chapter) of a book).

Well. We have our interface now (An interface is what the user visually gets; In our case, a small form with a text-box and 5 buttons), but we never added any code. If we’d run the code now (use F5, or the button in the ToolBar), we’d see the interface, but it wouldn’t do much. This is where Events step in.

Events

Let’s analyze what a user will be expecting when he sees your interface. He’ll notice he can use the TextBox to enter numbers, and the buttons for performing various mathematical functions. When he types a number made up out of more than one number, nothing has to happen; it’s only when he clicks a button that something will happen. Schematically, the following events will happen.

First, the user will enter a number. Nothing happens, because we cannot be sure of whether or not the user wants to type more numbers; instead, we’ll wait until the user presses a button, and take it that at that point, he wants to perform a calculation on that number. For this week, we will just add functionality to the plus, minus, divide and multiply buttons. We will deal with the ‘=’ button in future articles. To keep things simple, this week we will just make the TextBox show the updated number every time a user clicks one of the buttons.

Now that we know the basic scheme (We’ll enhance this in future articles), let’s look at the events (user-actions) in this scenario. We already determined that when text is entered, nothing will happen. However, when a user clicks a button, we do want something to happen. In Visual Basic terms, this is the definition of an ‘event’. An action, recognized by an object, for which you can write code to respond. . (Taken from the MSDN). For a CommandButton, the click-even is the default event. If you’d double-click the first button (cmdPlus), you’d be taken into the Code Window, and specifically to the ‘cmdPlus_Click()’ event. (Click is the default event for a CommandButton). It means the user supplied a number, and then wants to add another number to it. So what we do is:

# We will take the current value of whatever is in the TextBox.
# We then use add the same number to itself.
# Lastly, we update the TextBox to show the new number.

Not very useful really, but for this example, it will do the trick.

The code for that would be this:

txtInput.Text = txtInput.Text + Val(txtInput.Text)

What we do here is we say the Text-property of the TextBox is equal to the value of the current Text-property, plus the value of the current Text-property. (The period tells Visual basic that we’re referencing an object, and want to access something belonging to that object. (In this case, the Text-property). Note that with value I’m talking about it’s numeric value, and not the value of the Text-property. We use the numeric value, because if a user would input a letter instead of a number, it wouldn’t really make sense. Suppose a user entered the letter ‘a’ instead of a number. a + a would not really make sense to a calculator. Val() is a Visual Basic function designed for that purpose. (We’ll see what Functions are in future articles).

Let me introduce you to another programming concept at this point.

Indentation

If you just typed in the code as supplied, your code would now look like this:

Private Sub cmdPlus_Click()
txtInput.Text = txtInput.Text + Val(txtInput.Text)
End Sub

Imagine hundreds, if not thousands of lines of code in that way. That wouldn’t be readable, would it? Instead, let’s throw in a TAB before the line we typed:

Private Sub cmdPlus_Click()
txtInput.Text = txtInput.Text + Val(txtInput.Text)
End Sub

Notice how that looks much better? It’s like a book; If Tolkien had written lord of the rings in plain text, with no formatting at all, no one would have gotten through the first few pages. Instead, a clever author uses paragraphs, chapters, and what not to make sure that whatever they say is structured. Do the same thing when you’re programming. Make sure that you, or anyone else reading your code will have an easy time reading the code. Take a look at how other people program.

Back to the calculator.

Go back to the Form. (In the Explorer Window, double-click on it). We’ll see the Click- events for our other buttons now. Just go through the same procedure as before (double-click the button, and add the code (Just with different mathematical functions added to it). In the end, your Code-Window will look like this.

Run the program again, punch in some numbers, and use the buttons. You’ll see that by adding code to the ‘Click’ event, we basically told our program what to do whenever a user clicked a button. Other events could be selecting a value from a presented list of options, closing the program, clicking a menu-option, etc. Basically every action a user takes can be seen as an event.

By the way. You might have noticed that when you were typing in the code, after you pressed the dot (‘.’), a little scroll able list popped up.

Intellitype

Because you were assigning a value to the TextBox’s property, Visual Basic recognized you were accessing the TextBox-control, and offered as nice list with possible properties. Quite handy when you’re not actually sure which properties are available, or which one you are looking for. Intellitype also showed up when you were working with the Val-function. It showed you the syntax for the Function there. Intellitype is your best friend while programming; it makes sure you don’t have remember everything about Visual Basic.