VB .NET Chapter 5 VB .NET Forms


Adding Menus to a Visual Basic .NET Form

In this section we’ll see how to add menus to a Visual Basic .NET form. These type of menus are very common to Windows programme. Visual Basic itself has many of these drop down menus - File, Edit, View, Project, Format, etc. And they’re very easy to add.

Start a new project. To your new form, use the toolbox to add a MenuStrip control:
The MenuStrip Item on the Toolbox
Double click the control to add one to your form. When you do, you'll notice two things. At the top of your form, you'll see this:
A menu has been added to the form
We'll see how to construct our menu soon. But notice the other things that gets added to your project. Examine the bottom of your screen, on the left. You'll see this:
The Menu Object
This is the control itself. If you click on this (it's highlighted above), you'll see that the Properties box on the right changes. There are many properties for the control. But there are lots of properties for the MenuItem object. The MenuItem object is the one at the top of the form - The one that says Type Here.
To start building your menu, click inside the area that says "Type Here". Type the word File:
Type a File Item
Now press the enter key on your keyboard. Your menu will look like this:
Th eItem has been added to the menu
To create items on your File menu, click inside the Type Here box. Enter the word New, and press the enter key on your keyboard again. Your menu will then look like this:
Add a New Menu Item in VB NET
Add an "Open" and a "Save" item to your menu in the same way. It should look like this:
Add Open and Save Menu Items
The final item we'll add to our menu is an "Exit" item. But you can add a separator between the "Save" and "Exit".
To add a separator, click inside the "Type Here" box. Instead of typing a letter, type the minus character "-" (in between the "0" key and the "+/=" key on your keyboard). When you hit your return key, you'll see the separator appear:
Add a menu Separator
Click inside the "Type Here" area, and add an Exit (or Quit) item. Click back on your form, away from the menu, to finish off. You should now have a File menu like this one:
The finished VB menu
To see what your menu look like, Run your programme. Click the File menu. We haven't added any code to the menu yet, so nothing will happen if you click an item on the menu. But it does look quite good. Very professional!


Adding code to a VB.NET menu


This tutorial assumes that you have completed the previous one.
Stop your programme and return to the design environment. Click File in Design Time to see your drop down menu. You can double click an item to open up the code window. But don't do that yet.
Another way to get to the code for an object is this:
  • Press F7 on your keyboard to go to the code window (CTRL +ALT + 0 in version 2012/2013)
  • Click the black arrow at the top, where it says General:
The code window for Form1
The Exit menu here is "ExitToolStripMenuItem". If you were to click that item, a code stub would open, ready for you to type your code.
However, "ExitToolStripMenuItem" is very difficult to remember. We can rename our menu items so that they are more descriptive. So do this:
  • Get back to your form by pressing Shift + F7 on your keyboard
  • Click the File menu to select it
  • Select your Exit (or your Quit) item (Careful not to click in the middle as this may open the code window.Click near the left edge somewhere.)
  • When you have the Exit item selected, look at the properties box on the right:
The properties box for the Exit item
  • Click inside the Name property
  • Change it to mnuExit (or mnuQuit)
  • Press your return key on your keyboard to confirm the change
Now press F7 (or CTRL + ALT + 0) again to bring the code window up. Click the drop down arrow of the General box, and you should see the new name appear (Notice that MenuItem6 has vanished):
The Exit item has been renamed
Click on your new mnuExit item.
Nothing will happen!
To jump straight to the code, you need to look at the drop down box opposite. It will probably say "Declarations". Click the arrow and you'll see a new list:
Select Click from the Declarations section
The items in the Declarations box are called Events. The Event you want is the Click event. So select that one from the list (we'll cover Events in more depth later). When you select Click from the list, you are taken straight into the code for that event. It should be like this one:
The code stub for the Exit menu
The code above has been tidied up to fit on this page; yours will all be on one line. But notice that it says mnuExit_Click.
Don't worry too much about what it all means; we'll get to that in a later section. What we want to do is add some of our own code, so that out Exit menu item actually does something.
There's only one line of code to add. It's this:
Me.Close( )
The word "Me" refers to the form. When your type the word Me, you'll see a list if items appear. Double click the word Close, then press your return key. Your code window should look like this:
The line Me.Close() has been added
(Again this has been tidied up to fit on this page.)
To test out your new code, run your programme. Click your File menu, and then click the Exit item. Your form should close down, and you'll be returned to the design environment.

Add a Sub Menu to your VB.NET Form

This tutorial assumes that you have completed the first one.
A sub menu is one that branches of a menu item. They usually have an arrow to indicate that there's an extra menu available. You will have seen these plenty of times in Windows programmes.
You can create our own sub menus quite easily. Try this:
  • Return to the Form view (Shift + F7 is a shortcut)
  • Click on your File menu so that you can see it all
  • Select the New item (Careful where you click. Click once on the left edge). You should see this:
Select the New item
  • Click on the "Type Here" just to the right of New
  • You'll see yet more "Type Here" areas:
A sub menu area appears
  • Type New Project, and then hit the return key on your keyboard
  • Type in New File and then click away from the menu, somewhere on the form
  • You will then have a menu like this one:
The two new items have been added
  • Save your work, and then run your programme. Click your new menu to see the following:
The New Sub Menu
Of course, none of the menu items work except the Exit menu. But you should have found that adding menus to your programmes is an easy matter with VB.NET.
One more thing we can do. If you look closely at a lot of menu items, you see that they have shortcuts attached. There's two types of shortcuts: An underline shortcut, and a key combination shortcut.

Add Shorcuts to your Menu Items

This tutorial assumes that you have completed the first one.
In the previous tutorial, you learned how to add Sub Menus to your VB .NET forms. In this part, you'll see how to add shortcuts to your menu items

Underline Shortcut

To add an underline, do this:
  • Click on your New menu item once. This will select it
  • Position your cursor before the "N" of New
  • Type an ampersand symbol (&)
  • Hit the return key on your keyboard
  • You should see this:
Notice that "N" of New is now underlined. If you want an underline shortcut, the ampersand character should be typed before the letter you want underlined.
Add underlines for the "F" of you File menu, the "O" of Open, the "S" of Save, and the "X" of Exit. When you're done, your menu should look like this one:
Time to see if your shortcut works. Run your programme. To use the underline shortcuts on menus, you first hold down the Alt key on your keyboard. Then type the underline character.
  • Hold down the Alt key while your programme is running (You might not be able to see the underlines until you press the Alt key.)
  • Press the letter "F" on your keyboard
  • Then press the letter "X" (for the Exit menu)
  • Your programme should close down
All that and you didn't have to write a single line of code!

 

Key combination shortcuts

A key combination shortcut is one that appears at the end of a menu item (Ctrl + X, for example). You can easily add this option to your own programmes. So try this:
  • In Design time, select the Exit item on your menu
  • Look at the properties box on the right
  • Locate the ShortcutKeys item:
ShortcutKeys Property in VB NET
  • Click the down arrow to reveal the following:
The Modifier is the key you press with your shortcut. For example, the CTRL key then the "X" key on your keyboard. Place a check inside the Ctrl box. Then select the letter "X" from the Key dropdown list, as in the next image:
Click back on your menu to see what it looks like:
Run your programme and test out the shortcut. Don't click the File menu. Just hold down the Ctrl key on your keyboard. Then press the letter X. Again, the programme will close down.
You can add these types of shortcuts to any menu item. Just remember to choose a different key stroke combination for each one. And don't have too many of them - they'll spoil the look of your menu!

Now that you know how to add Menus, Sub Menus and Shortcuts it's time for you to complete your own menu bar. Click the project below to see what you need to do. It's not very difficult! In the section after the project, you'll see how to add code for your new menu bar.

A VB .NET Menu Project


his tutorial assumes that you have been following along from the first one.Add the following Main Menu items to the menu bar you have already designed in this section:
  1. Edit
  2. View
On your Edit Menu, place the following menu items:
  • Undo
  • Cut
  • Copy
  • Paste
On your View Menu, place the following menu items:
  • View Textboxes
  • View Labels
  • View Image
Just like you did with the Exit menu item, Change the Name property of ALL menu items. Do not leave them on the defaults of "MenuItem1", "MenuItem2", etc. (You should change the Name property to something relevant, and use the prefix mnu. For example, the Undo item could have the Name mnuUndo.)
  • Add an underline shortcut for ALL menu item
  • Add a least one key combination shortcuts per drop down menu (you already have one on the File menu, so this doesn't count)
When you have finished, your menus should look like these (though you can use different key combinations, if you like):
Edit Menu
The Edit Menu
View Menu
The View Menu
  • Write code to display a message box whenever a menu item is clicked, or its shortcut used. The message box should explain what the menu item will do when it's fully implemented.
There's only one line of code to write for each menu item. You can get at the code for the click event of each menu item in exactly the same way that you did for the Exit menu item.
Good Luck!

The Open File Dialogue Box

For the last project, you designed a form interface that had a File, Edit and a View menu. In this section, we'll write code so that your menu items actually do something other than displaying message boxes. In other words, the Edit > Cut menu will really cut text, and the Edit > Pastemenu will really paste text.
So open up the project you completed for the previous section. Comment out or delete any message box code. (You comment out code by typing a single quote character at the start of the line. The line will then turn green, and will be ignored when the programme is run.)
We'll start with the File > Open menu.


The Open File Dialogue Box

In most programmes, if you click the File menu, and select the Open item, a dialogue box is displayed. From the dialogue box, you can click on a file to select it, then click the Open button. The file you clicked on is then opened up. We'll see how to do that from our menu. (Except, the file won't open yet - only the dialogue box will display, and then name of the chosen file. You'll learn how to open files in a later section.)
First, place two textboxes on your form. In the properties box, locate the MultiLine property. It is set to False by default (which is why you can't change the height of textboxes). Change this value toTrue.
Type some default text for the Text Property of textbox1. Change the Font size to 14 points.
Your form should now look something like this one:
What your form should look like now
We'll work with these textboxes when we do the Edit menu. So let's leave them for now.
When we click on File > Open from our menu, we want the Open dialogue box to appear. This is fairly straightforward in VB.NET. In fact there is even a control for it!
Open up your toolbox, and locate the control called "OpenFileDialog". You might have to scroll down to see it. But you're looking for this:
The Open File Dialog Control
Double click the control to add one to your project.
But notice that the control doesn't get added to your form. It gets added to the area at the bottom, next to your menu control:
The Object area in VB .NET
The shaded area surrounding the control means that it is selected. If you look on your right, you'll see the properties that you can use with the control.
Click on the Name property and change the name to openFD. When you change the name in the properties box, the name of the control at the bottom will change:
The Control has been renamed to openFD
We’ll now write some code to manipulate the properties of our new control. So do the following:
  • Access the code for your File > Open menu item. (To do this quickly, you can simply double click the Open item on your menu bar. Or press F7 (CTRL + ALT + 0 in version 2012) to access the Code View.)
  • Click the name of your menu item from the left drop down box at the top of the code
  • Then select the Click event from the drop down box to the right
  • Your empty code should be this (the code below has underscore characters added, so that it can fit on this page):
Private Sub mnuOpen_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuOpen.Click
End Sub

With you cursor flashing between the two lines of your code, add the following:
openFD.ShowDialog()
When you typed a full stop after the openFD, you probably saw a list box appear. You can just double click the ShowDialog() item to add it to your code.
But this method of the OpenFileDialog control does what you'd expect it to do: Shows the dialogue box. You can even test it out right now. Press F5 to run your programme. Then click the Open item on your File menu. You should see an Open dialogue box display.
Return to the design environment, and we'll explore some more things you can do with this Dialogue box control.


The Initial Directory

You can set which directory the dialogue box should display when it appears. Instead of it displaying the contents of the "My Documents" folder, for example, you can have it display the contents of any folder. This done with the Initial Directory property. Amend your code to this:
openFD.InitialDirectory = "C:\"
openFD.ShowDialog()
Run your programme again, and see the results in action. You should see the contents of the "C" folder on your hard drive (if you root folder is called something else, change the code above).

The Title Property

By default, the dialogue box will display the word "Open" as a caption at the top of your dialogue box. You can change this with the Title property. Add the line in Bold to your code:
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a Text File"
openFD.ShowDialog()
Run your code again, and Click File > Open from your menu. You should see this at the top of the Open dialogue box:
Notice the new white title on the blue background

The Open File Dialogue Box Filter Property

This tutorial follows on from the previous section
In the previous section, we saw how to add an Open File Dialogue to our menus. We then saw how to add an Initial Directory and a Title property. In this section, we'll learn about the Filter property.

The Filter Property

In most dialogue boxes, you can display a list of specific files that can be opened. These are displayed in the "Files of Type" drop down list. To do this in VB.NET, you access the Filter property. We'll restrict our users to only opening Text files, those that end in the extension ".txt".
The following code shows how to use the filter property:
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a Text File"
openFD.Filter = "Text Files|*.txt"
openFD.ShowDialog()
Run your code. Click File > Open on your menu, and then click the arrow on the drop down box for "Files of Type". You should see this:
Only text files can be opened here
Or this, in laster versions of the Windows operating system:
Filter box in Windows 7
You can add a little bit extra to the description part of the filter, if you like. This will server a s a reminder of just what the extension is. Try amending the line to this:
openFD.Filter = "Text Files(*.txt)|*.txt"
When you run your code, you see this in the Files of Type area (XP only. Vista and Windows 7 already have the extra information.)::
The file extension has been added
If you scroll across your Open dialogue box, you should see only text files displayed (you'll still see folders). If you can't see any files at all, double click a folder and explore. You'll soon see something like this:
Only text files are showing
To display files of more than one type, add a Pipe character between each filter. In the code below, two file types are specified, text files and Microsoft Word documents:
openFD.Filter = "Text Files|*.txt|Word Files|*.doc"
When the programme is run, you should be able to see two file types in the list:
File Filters in Windows 7

Select a File from the Open File Dialogue Box

You'll notice from the previous section that if you select a file and click the Open button, nothing happens. That's because the Open dialogue boxes doesn't actually open files! It only displays a list of files that CAN be opened, if you were clever enough to write the code. We'll be writing the code that does the opening (and the saving) in a later section. But you need to be able to get the name of the file. The Open Dialogue box has a property that returns the file name that was selected. Not surprisingly, it's called FileName:
OpenFD.FileName
However, this is a property that returns a value (a string value). The value is the name of a file. So you have to assign this value to something. We can assign it to a new variable:
Dim strFileName As String
strFileName = OpenFD.FileName
The value in the variable strFileName will then hold the name of the file selected. So change you code to this (new lines in bold):
Dim strFileName As String
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a Text File"
openFD.Filter = "Text Files|*.txt"
openFD.ShowDialog()
strFileName = OpenFD.FileName
MessageBox.Show( strFileName )
Run your programme, and click your File > Open menu. Navigate to where you have some text files. Click one to select it. Then click the Open button. You should see the name of the file displayed in your message box:
The selected file has been returned
Notice that the location (the path) of the file is also displayed.
One thing you may have noticed is that if you select a file, then click the Cancel button, the message box still displays. But it will be blank, or just say OpenFileDialog1. In your code, you will only want to do something with a file if the Cancel button is NOT clicked.
You can test to see if it was clicked by assigning the openFD.ShowDialog() to an integer:
Dim DidWork As Integer = openFD.ShowDialog()
You can then test what is inside of the DidWork variable. If the cancel button is clicked, the result of the action is stored by VB.NET in this property:
DialogResult.Cancel
You can compare the two in an if statement:
If DidWork = DialogResult.Cancel Then
MsgBox("Cancel Button Clicked")
Else
strFileName = openFD.FileName
MsgBox(strFileName)
End If
In the code above, you're only opening the file if the Open button was clicked. The code is a bit more complicated, but study it for a while and it will make sense!

The SaveFileDialog Control

The save dialogue box works in the same way as the Open dialogue box. However, you can't use the same control. If you examine the Toolbox, you'll see a control called SaveFileDialog:
The SaveFileDialog control in VB Net
Double click this control to add one to your project. If you look at the bottom of the screen, you'll see the control added there, rather than onto your form:
The control is added to the Object area
In the image above, the control is selected. Changed the Name property of your control to something more manageable. Change it to saveFD. (You learned how to do this in a previous section.)
Access the code for your File > Save menu item. Then add the following code:
saveFD.ShowDialog()
Your code window should look like this one (Again, underscores have been added to the first line to fit on this page):
The code for the Save menu
Run your programme, then click your File > Save menu item. You should see the Save Asdialogue box appear.
Just like the Open control, you can use the properties of the Save control on your dialogue boxes. Try changing these properties, just like you did with the Open properties:
Initial Directory
Title
Filter
FileName
There's another useful property you can use with the Save control - the Overwrite prompt. When you set this property, a message box pops up warning you that the file will be overwritten, and do you want to continue. To use this property, the code is this:
saveFD.OverwritePrompt = True
However, just like the Open box, when you click the Save button no file is actually being saved. You have to write your own code for this. You'll learn how to do this in a later section. For now, let's move on to the Edit menu.

Cut, Copy, Paste and Undo in VB .NET

If you haven't already, add two textboxes to your form and set their MultiLine property to True. What we'll do now is to get the following menu items to work: UndoCutCopy and Paste. We'll start with Copying:

The Copy Menu

If you type Textbox1 in your code window, then a full stop, you get a list of properties and methods available to the textbox. Scroll up to the top and locate the Copy method:
Copy
VB NET 2012 Intellisense menu
Notice the tool tip in yellow in the 2010 version. It's telling you what this method does - copies the current selection to the clipboard. The clipboard is a temporary storage area available to most Windows applications. When you invoke the Copy method of the textbox, any selected text is place in this temporary storage area for you. You don't have to write any other code.
So access the code for your Copy menu item, and add this line to it:
Textbox1.Copy()
Your code window should look something like this:
Code to Copy text in VB NET
That's all there is for the copy menu! But nothing visible will happen when you run your code. Let's paste it into the second textbox.


The Paste Menu

Again, there's only one line of code to write. It's this:
TextBox2.Paste()
Notice that we're saying paste to textbox2. Because the copy menu places the text from textbox one onto the clipboard, you only need this one line of code. You're saying "Whatever is on the Clipboard, paste it into Textbox2".
So add that line to your Paste menu item. Your code window should look like this:
Pasting Text in VB NET
Time to test it out. Run your programme. Select all the text in textbox one (it might already be selected), then click Edit > Copy from your menu.
Click inside the second textbox. Then click Edit > Paste from your menu. The text should appear in textbox two.

The Cut Menu

Access the code for you Cut menu item. Add the following code to it:
TextBox1.Cut()
Run your programme, and select the text in textbox one. From your menu, click Edit > Cut. The text should disappear (it's on the clipboard, though). Click inside textbox two, and click Edit > Paste. The text should be pasted over.

 

The Undo Menu

For the Undo menu, add this line of code:
TextBox1.Undo()
Run your programme. Then select the text in textbox one. Click Edit > Cut and the text disappears. Now click Edit > Undo. The text reappears.
The Edit menu we implemented is only a simple one. But it does demonstrate what you can do with VB.NET and menus.

We'll complete out look at menus by coding for the View menu you added to your form. In the process, we'll take a look at pictures boxes, as well as seeing how easy it is to hide and disable controls on a form.

How to Show and Hide Controls

The items on our view menu are:

View Textboxes
View Labels
View Images
Although these are not terribly practical examples of what to place on a View menu, they will help us to demonstrate a few useful techniques. The first of these is how to show and hide controls.

The View Textboxes menu item

Controls on a form can be hidden or shown as the need arises. The process is quite easy. Access the code for your View Textboxes menu item. Type the following for the menu item:
Textbox1.Visible = False
Textbox2.Visible = False
Run your code and test it out. Click View > View Textboxes. The two textboxes you added should disappear.
To hide a control, simply set it's Visible property to False. If you want to get it back, show a control by setting the Visible property to True.
A good idea is to have the ability to toggle a control on and off: One click of a menu item could hide the control, and a second click could show it again. You can do that with your menus.
Each item on your menu has a Checked property. If set to True, you'll see a tick appear next to the menu item. As in the image below:
The selected menu item has a tick next to it
You can use this Checked property as a toggle: If the menu item is ticked, display the textbox; if it's not ticked, hide the textbox.
Delete or comment out the line of code for your View Textboxes menu item. Add the following line in its place (this assumes that you've Named your View Textboxes menu item as mnuViewTextboxes. If you've named it something else, changed the part before the full stop):
mnuViewTextboxes.Checked = Not mnuViewTextboxes.Checked
This line toggles the Tick on and off. The part before the equals sign sets the Checked property of our menu item. The part after the equals sign sets it to whatever it's NOT at the moment. So if Checked is True, it's NOT False. In which case, set it to False.
Run your code and test it out. Click View > View Textboxes. Have a look at the menu again, and you'll see a tick appear. Click View > View Textboxes again and the tick will disappear.
We can show the textboxes if there's a tick next to View Textboxes. Just test the value of the Checked property in an If Statement. Add this If Statement just below your first line:
If mnuViewTextboxes.Checked = True Then
TextBox1.Visible = True
TextBox2.Visible = True
Else
TextBox1.Visible = False
TextBox2.Visible = False
End If
So the If Statement examines the Checked property of the menu item. If it's True, make the textboxes Visible ; Else, we set the Visible property of the textboxes to False.
Before you run your code, return to the Form view by holding Shift + F7 on your keyboard. When you have your form displayed, and not the code, click on textbox1 to select it. In the property box, locate the Visible property and set it to False. Do the same for texbox2. When your form runs, the two textboxes will then be hidden.
Now run your programme and test out your new menu. Click View > View Textboxes and see if they toggle on and off.

Exercise

Add two labels to your form. Write code to toggle the labels on and off. The two labels should disappear with the textboxes. And they should reappear when the menu item is toggled to the on position

The View Images menu Item

Download the images you need for this tutorial

It's easy to add an image to your form with VB.Net. To insert an image, locate the PictureBoxcontrol in the toolbox (under Common Controls). Either double click the control, or hold down your mouse on the form and draw one out. You should see something like this:
The Picture Box control
Change the Height and Width properties of the Picture Box to 100, 100. (You can change both from the Size property.) You'll have a small square. To make it stand out more, locate theBorderStyle property. Change the value to Fixed3D. Your Picture Box will then look like this:
A fixed3d picture box
To add a picture at design time, locate the Image property in the properties box:
The Image property of the Picture Box
Download and unzip the image at the top of the page. Then click the button with the three dots on it. A dialogue box appears. Locate an image. Select it, and then click Open in the dialogue box. The image will appear in your Picture Box:
An image in a picture box
If you select an image that is too big for the picture box, only part if it will be visible. The Picture Box control does not resize your image.
You can, however, set another property of the picture box - the SizeMode property. Set this toAutoSize and your picture box will resize to the size of your image.

 

Insert an Image with your View Menu

You can use your open file dialogue box again to specify an image for the user to select. We'll do this from the View Images menu item.
Highlight you code for the mnuOpen item. (If you haven't yet coded for the File > Open menu item, click here.) Copy the first five lines, these lines:
Dim strFileName As String
openFD.InitialDirectory = "C:\"
openFD.Title = "Open an Text File"
openFD.Filter = "Text Files|*.txt"
Dim DidWork As Integer = openFD.ShowDialog()
Paste them to your mnuViewImages menu item code. Change the Title property to this:
openFD.Title = "Open an Image"
And change the Filter property to this:
openFD.Filter = "jpegs|*.jpg|gifs|*.gif|Bitmaps|*.bmp"
Run your code and click your View Images menu item. You should see the Open dialogue box appear. If you look at the "Files of type" box, you should see this:
Available Image Types
Or this in later version of the Windows operating system:
image types in Windows 7
You should now be able to see only the three image formats we've specified.
To insert an image into your Picture Box, some new code is needed. Again though, we'll wrap it up in an If Statement.
Add the following code below the lines you've just added:
If DidWork <> DialogResult.Cancel Then
strFileName = openFD.FileName
PictureBox1.Image = Image.FromFile(strFileName)
openFD.Reset()
End If
There's only two lines you haven't met yet. The first is this line:
PictureBox1.Image = Image.FromFile(strFileName)
Previously, you were loading the image into the Image property of PictureBox1 directly from the Properties Box (by clicking the grey button with the three dots in it). Here, we're loading an image into the Image property using code. The way you do it is with the FromFile method of the Image Class.
Although that might be a bit baffling at this stage of your programming career, all it means is that there is some in-built code that allows you to load images from a file. In between round brackets, you type the name and path of the file you're trying to load. Since our file name has been placed inside of the strFileName variable, we can just use this. You can then assign this to the Imageproperty of a Picture Box.
The last line, openFD.Reset(), will reset the initial directory of the open file dialogue box. To see what this does, comment out the line (put a single quote at the start of the line). Run your programme and Click View > View Images. Insert an image and then click File > Open. You'll notice that the files displayed in your dialogue are from the last directory you opened, rather than the one you set with "InitialDirectory = "C:\". By resetting the open dialogue box control, you're fixing this problem.

OK, that concludes our look at menus. We'll create a new programme now, and explore checkboxes, radio buttons and Group Boxes

Check Boxes in VB .NET

Two more useful controls in the Visual Basic toolbox are the Check box and the Option Button. You use these when you want to give your users a choice of options. We'll add both of these to a new Form, and then combine them with a Select Case statement to read what the user has chosen.

Check Boxes

So start a new project. Locate the Checkbox control in the toolbox, under Common Controls. Double click the control and a Checkbox appears on your new Form
You'll see that the Checkbox has the Text property of CheckBox1 by default, and a Name of CheckBox1. If you were to double click again on the Checkbox icon in the toolbox, the new control would be called CheckBox2.
The problem with this approach is that by double clicking each Checkbox, you have several individual Checkboxes. And if you wanted to move them around you'd have to move each Checkbox separately. There is a way to group all your Check Boxes together, and move them around as one - by using a Group Box. (You can use a Panel control as well, but we'll stick with the Group Box.)
So, click on your Checkbox with the right mouse button. From the menu that pops up, select delete to get rid of it.
Now locate the Group Box control in the toolbox:
A GroupBox in the VB NET toolbox
It's better to draw this one on the form, rather than dragging and dropping. When you've added one, the only thing you should have on your Form is a Group Box.
We're not going to be using many of the Properties in the Group Box Property box. But click on your Group Box to select it, and change to the Text Property to "Soaps". Change the Font Property to anything you like. You should now have a Form like this one
A Group Box on a VB .NET form
The Group Box we just added will hold our Checkboxes. It acts as a container for the controls. To move the Checkboxes about, we can just click on the Group Box to select it, and drag and drop the Group Box somewhere else. The Checkboxes will all move with the Group Box. Let's add some Checkboxes to it.
You CAN'T double click a checkbox and add it to a Group Box. The only way to add a control to a Group Box is to draw one on the Group Box.
  1. Click once with your left mouse button on the Checkbox icon in the VB toolbox
  2. Move your mouse pointer over to the inside of the Group Box. The mouse pointer will change to a cross
  3. Hold down you left mouse button inside the Group Box. Keep the button held down, and drag outwards. Release the left button when you're happy with the size. You can always resize it later.
  4. Add 5 Checkboxes to your Group Box
  5. Change the Text property of each of your Checkboxes to any five Soap Operas. Your Form should now look something like the one below:
What your form should look like now
Run your programme to test it out. Click inside a Checkbox to select an item. Click again to deselect it. When you've finished, return to the Design Environment and click on the Group Box itself to select it. Make sure the Group Box IS selected, and not one of your Checkboxes. You can now drag the Group Box around your Form and all the Checkboxes will move with it.
The point about having Checkboxes is to offer your users multiple choices. We'll now write some code to get the choices made by the user. All the Checkboxes with ticks inside them will have their Text displayed in a Message Box.

The Checkbox Code

If you click on any one of your Checkboxes and examine its Properties in the Property box, you'll notice that it has a CheckState Property. Click the down arrow to see the options this CheckStatehas.
The CheckState property
As you can see, you are given three options: Unchecked, Checked, Indeterminate.
If a checkbox has been selected, the value for the CheckState property will be 1; if it hasn't been selected, the value is zero. (The value for the Indeterminate option is also zero, but we won't be using this.)
We're only going to test for 0 or 1, Checked or Unchecked. You can do the testing with a simple If Statement. Like this:
If CheckBox1.CheckState = 1 Then
MsgBox("Checked")
End If
After you type the equal sign, though, VB will give you a drop down box of the values you can choose from. So the above code is the same as this:
If CheckBox1.CheckState = CheckState.Checked Then
MsgBox("Checked")
End If
Whichever you choose, the Statement will be True if the checkbox is ticked and False if it isn't.
Add a Button to your Form and put that code behind it (either of the two, or test both). When you've finished typing the code, run your programme. Put a tick inside Checkbox1, and click your button. You should get a Message Box popping up.
Amend your code to this:
If CheckBox1.CheckState = CheckState.Checked Then
MsgBox("Checked")
Else
MsgBox("Not Checked")
End If
An alternative to Else is ElseIf. It works like this:
If CheckBox1. CheckState = 1 Then
MsgBox "Checked"
ElseIf Checkbox1. CheckState = 0 Then
MsgBox "Unchecked"
End If
When using the ElseIf clause, you need to put what you are testing for on the same line, just after ElseIf. You put the word Then right at the end of the line. You can have as many ElseIf clauses as you want. In other words, it's exactly the same as the first "If" line only with the word "Else" in front "If".


Add 4 more If Statements to check for the values in your other Checkboxes :
Checkbox2.CheckState, Checkbox3.CheckState, etc.
We're now going to get rid of the Message Boxes inside the If Statements. So either comment out all your MsgBox lines, or delete them altogether.
Instead, we'll build up a String Variable. So add a String Variable to the code for your button, and call it message.
The message variable needs to go inside the If Statement. If the user has checked a Box (If its CheckState property is 1), then we build the message. We need to remember what is inside the message variable, so we can just use this:
message = message & Checkbox1.Text & vbNewLine
That way, every time an option is Checked, Visual Basic will keep what is in the variable called message and add to it whatever the text is for the Checkbox.
So add that line to your If Statements. Something like this
If Checkbox1.CheckState = 1 Then
message = message & Checkbox1.Text & vbNewLine
End If
If Checkbox2.CheckState = 1 Then
message = message & Checkbox2.Text & vbNewLine
End If
And at the end of your If Statements, on a new line, add this:
MsgBox "You have chosen " & vbNewLine & message
Here, we're building a text message for out Message Box. We're saying our Message Box is to contain the text "You have chosen " And a New Line And whatever is inside the variable called message.
When you've finished, Run your Programme to test it out. Put a tick inside all of your Checkboxes. When you click your button all your Soap Operas should appear in the Message Box. Check and Uncheck some options, and click the button again. Only those items that are selected should appear in your Checkbox.
So, we can test to see which Check Boxes a user has ticked, and we can keep a record of those choices for ourselves.
What we can also do is count how many Check Boxes were ticked. We can then use a Select Case Statement to display a suitable message.
Keeping a count is straightforward. First we set up an integer variable called counter, and set it's value to zero.
Dim counter As Integer = 0
Then we can just keep adding one to whatever is in this counter variable. In other words, every time a Checkbox has a value of 1 (is ticked), we can add one to our counter (increment our variable).
We can add this straight into our If Statement, on a new line after the message code.
counter = counter + 1
So your code would be this:
If Checkbox1.CheckState = 1 Then
message = message & Checkbox1.Text & vbNewLine
counter = counter + 1
End If
To test that your counter is working, you can add a second message box to the end of the code, just below your first message box:
MsgBox("Counter = " & counter)
Or adapt your first message box:
MsgBox("You have chosen " & counter & " soaps")
Now that we have a way to count how many Checkboxes are ticked, we can add a Select Case Statement.

Exercise I

Add a Select Case Statement to the end of your code to test whatever is inside the variable called counter.
Remember what the format is for a Select Case? It's this:
Select Case VariableName
Case 0
MsgBox "You obviously don't watch soaps!"
End Select
If you have 5 Check Boxes on your Form, then the maximum value that counter will hold is 5. So you only need to go up to Case 5.
Add suitable messages for each Case that you're testing for.

This has been quite a long lesson, so give yourself a big pat on theback if you got through it!

Add Option Buttons to a VB .NET form


Radio Buttons, sometimes called Option Buttons, are used when you want to restrict a user's choice to one, Male/Female, for example. A Checkbox would be no good here, because a user could tick both boxes. You want to force your users to pick only one from your list of options.

Adding Radio Buttons to a Form is exactly the same process as adding a Checkbox. Again, we'll add some Radio Buttons to a Group Box, and write code to extract what the user has chosen.
  1. Add a Group Box to your Form.
  2. Set the Text Property of the Group Box to "Best Sit Com of all time"
  3. Set the Font options to anything you like
  4. Place five Radio Buttons into your Group Box (By default, they'll be called "Option1", "Option2", "Option3", etc
  5. Set the Text Property of the Five Radio Buttons to Only Fools and Horses, Dad's Army, Blackadder, Fawlty Towers, Vicar of Dibley
  6. Your Form should now look something like this:
Radio Button Form in VB NET
Run your programme and test to see if you can indeed only select one item from the list.
The reason you can only select one is that all the radio buttons are placed in the same group box. You can place another set of radio buttons in a second group box, and these would work independently of the set of radio buttons in the first group box.

To test which Sit Com was chosen, you can use an If … Elseif Statement. You can do this because only one of the radio buttons will be True if selected: all the others will then have a value of False.
So place a Button on your form. Set the Text property to something appropriate. Then double click your new button to open up the code window. Type the following code (Notice that the Property is now Checked, and not CheckState):
Dim ChosenSitCom As String
If RadioButton1.Checked = True Then
ChosenSitCom = RadioButton1.Text
ElseIf RadioButton2.Checked = True Then
ChosenSitCom = RadioButton2.Text
ElseIf RadioButton3.Checked = True Then
ChosenSitCom = RadioButton3.Text
ElseIf RadioButton4.Checked = True Then
ChosenSitCom = RadioButton4.Text
ElseIf RadioButton5.Checked = True Then
ChosenSitCom = RadioButton5.Text
End If
MsgBox("You voted for " & ChosenSitCom)
By using If … ElseIf we can check which radio button a user selected. The Text property from the chosen radio button is then placed in a String variable called ChosenSitCom. At the end, we then display the selected radio button in a message box.
Run your programme and test it out. Select a Sit Com, and then click your Button. You should see the item you selected displayed:

Exercise

Add a Textbox to your Form. Write code to transfer a chosen Sit Com to the Textbox when the button is clicked. Add a label next to the Textbox with the Caption "You Voted For. . . "

And that's all there is to adding Option Buttons to your VB .NET forms. In the next section of the course, we'll take a look at error checking.

Comments