Beginning Visual Basic (Visual Studio 2010) - Project 6

List Boxes, Check Boxes, and Group Boxes

Project 6

Close your last project and creating a new one

If you still have the Project5 project open, select the Close Project item on the file menu to close it.

With no open projects, click on the Project... option next to Create: on the Start Page, or pick New Project item on the File drop-down menu. 

The Add New Project dialog appears.  With the Windows Forms Application template selected, type Project6-7 for the name and click the OK button—We will also be using this project for project 7.  Now click the Save All button on the toolbar to save the project.  Be sure to uncheck the Create directory for solution option on the Save Project dialog box.  Do not change the default Location path and click the Save button. 

This creates a new folder inside the My Documents\Visual Studio 2010\Projects\  folder named Project6-7:

        My Documents\Visual Studio 2010\Projects\Project6-7

Rename the Form file and the Form

With the form file (Form1.vb) selected in the Solution Explorer window, the Properties window directly below it displays it's File properties.  Click on the File Name property and type frmProj6.vb (don't forget to include the .vb extension).  To display the properties of the form in the Properties window, click once on the blank Form, which should be displayed on the left side of the screen in the Design window.  Make sure the Name property—which is in parentheses (Name) at the top of the property list so that it's easy to find—is frmProj6.  Then scroll the properties windows down and change the Text property to Project 6.

Before going on, click on the Save All button on the toolbar to save your project.
 


Adding items to a Listbox, deleting items and clearing it

For your sixth project you will create a program that allows the user to type names into a TextBox and add those names to a ListBox (with an Add button).  The user will be able to select names in the ListBox and remove them one at a time (with a Delete button), or clear the ListBox completely (with a Clear button).  They will also be able to hide individual controls with a set of Checkboxes that are inside a GroupBox with the caption Hide.  You will do this project in 2 parts.

Here’s what Part A requires (See the first illustration in Part A below):

Here’s what Part B requires (See the first illustration in Part B below):

Part A

Use the illustration below as a guide. Place the TextBox (top) and ListBox (below the Textbox) as shown. Add 4 Buttons, and a Label (Name:) for the Textbox:

Note: No Properties/Procedures Table is provided for this project. Be sure to name each control as you place it on the Form. Please use the Naming Conventions for your Controls and Variables that we have followed so far in this class.

Adding items to a ListBox The Add button

To add items typed into the Textbox (txtName) to the ListBox (lstNames), use the Add method of the Items collection of the ListBox.  The Items collection is a collection of all the entries in a ListBox.  The single parameter required by the Add method is the object to be added to the collection.  The following line of code adds the value in the Text property of the txtName TextBox to the ListBox:

'Use the Add method of the listbox's Items
'    collection to add
the value in txtName.Text
'    to the lstNames listbox.

lstNames.Items.Add(txtName.Text)

Add the above line of code to the btnAdd_Click event procedure.

Testing the program so far

Click on the Save All button on the toolbar to save your project.  Now click the start debugging button to run the project.  Type your name in the txtName textbox and click on the Add button.  Did the name get added to the lstNames listbox?   Type another name in the txtName textbox, and click the Add button again.  Did the new name get added to the lstNames listbox below the first name you added?  Clear any text from the txtName textbox and click the Add button once.  Now type a new name in the txtName textbox and click the Add button.  Do you see a blank entry between the last name and the second name you added to the listbox?

To prevent the user from adding blank entries to the listbox, we need to make sure that the Text property of the txtName textbox isn't empty before adding the value it contains to the listbox.  Modify the above code in the btnAdd_Click event procedure to include the following If-Then test:

'Be sure that txtName.Text.Length is greater
'    than 0 before adding it's contents to the
'    lstNames listbox.

If txtName.Text.Length > 0 Then
    'Use the Add method of the listbox's Items
    '    collection to add the value in txtName.Text
    '    to the lstNames listbox.

    lstNames.Items.Add(txtName.Text)
End If

The above code tests the Text.Length property of the txtName textbox.  If txtName.Text.Length is greater than 0 then the textbox isn't empty and we add it's contents to the lstNames listbox.  This is also where we can use a MessageBox to instruct the user on how to use the Add button, by modifying the above code to include an Else section, like this (the italicized code):

'Be sure that txtName.Text.Length is greater
'    than 0 before adding it's contents to the
'    lstNames listbox.

If txtName.Text.Length > 0 Then
    'Use the Add method of the listbox's Items
    '    collection to add the value in txtName.Text
    '    to the lstNames listbox.

    lstNames.Items.Add(txtName.Text)
Else
     'Display an instructive MessageBox 
    MessageBox.Show("The Name textbox is empty! Please" _
                                
vbCrLf & "type the name to be added.",  _
        
                         "Illegal Operation",   _
        
                        MessageBoxButtons.OK,   _
        
                        MessageBoxIcon.Exclamation)
End If

The four parameters being passed to the Show method of the MessageBox class, in the above code, have been broken onto multiple lines for readability.  Note: You can break a single long line of code onto multiple lines by adding a space and underline character at the end of each line.   Also note that in the message line above we have inserted vbCrLf, which is a visual basic constant for a carriage return and linefeed, so that the message is broken onto two lines as shown in the illustration below.

With the above code, if the user tries to click the Add button without typing a name in the txtName textbox, we display a message box that looks like this:

A call to the Show method of the MessageBox class requires 4 parameters, which are:

  1. The message string.  This is the message that is displayed in middle of the message box.
  2. The caption string. This is the string that appears in the caption bar of the message box.
  3. The MessageBoxButtons specification.  This determines which buttons are displayed on the message box.  Several button combinations are available.  This message box only requires an OK button to close it (MessageBoxButtons.OK).
  4. The MessageBoxIcon specification.  This determines which, if any, icon is displayed on the message box.  Several eye catching icons are available to help get the user's attention when the message box is displayed.

The code in your btnAdd_Click event procedure should now look like this:

Testing the program so far

Click on the Save All button on the toolbar to save your project.  Now click the start debugging button to run the project.  Type your name in the txtName textbox and click on the Add button.  Now clear the txtName textbox and click the Add button.  Is the message box displayed?

Making the Add button more user friendly

As it is now, after clicking on the Add button the user must click in the txtName textbox to give it the focus and manually erase the previous name they had typed, before they can type a new name.  To make adding names more user friendly, we can move the focus and clear the txtName textbox for the user in our code.  Add the following two lines of code after the End If statement at the bottom of the btnAdd_Click event procedure:

'Clear the name that was added
'    from the txtName textbox.

txtName.Clear()
'Move the focus to the txtName
'    textbox.

txtName.Focus()

Testing the program so far

Run the project and add a few names to the listbox.  Is the program easier to use now? 

Removing items from a ListBox - The Delete button

There are at least a couple of ways of removing items from a ListBox.  We could use the Remove method of the Items collection, with a line of code that looks like this (do not type this code):

lstNames.Items.Remove("Jerry")

This code would remove the first Jerry entry from the lstNames listbox.  This method won't work for us because we want to remove an entry that the user has clicked on in the listbox.  The RemoveAt method of the Items property let's us remove an entry from a listbox by specifying it's location (Index) in the list.  All the entries in a listbox can be referenced by an Index value which is their location in the list.  The first entry (at the top) in a listbox is in the 0 (zero) location.  The second entry is at 1, the third is at 2, etc.  The following code example will remove the third entry in the lstNames listbox with the RemoveAt method (do not type this code):

'Remove the third entry (0,1,2) from
'    the lstNames listbox
.
lstNames.Items.RemoveAt(2)

What we need to determine is the index value of the item in the listbox that the user has selected, and remove that item.  Fortunately, listboxes come with a SelectedIndex property, which is always equal to the index value of the selected entry in the listbox.  So the line of code above can be modified to include lstNames.SelectedIndex to remove the entry in the listbox that the user has selected, like this:

'Remove the selected item (SelectedIndex)
'    from the lstNames listbox
.
lstNames.Items.RemoveAt(lstNames.SelectedIndex)

Add the above line of code to the btnDelete_Click event procedure.

Testing the program so far

Click on the Save All button on the toolbar to save your project.  Click the start debugging button to run it and add a few names to the listbox.  Click on one of the entries in the listbox to select it and then click on the Delete button.  Was it deleted?  Now click on the Delete button again while no entry in the listbox is selected.  You should see the following error message:

Our lstNames.Items.RemoveAt(lstNames.SelectedIndex) line of code is highlighted and the error message says: InvalidArgument=Value of '-1' is not valid for 'index'. If you hold your mouse pointer over SelectedIndex in the highlighted line of code, a popup message should match the following illustration (SelectedIndex is equal to negative one!):

This shows us that the SelectedIndex property, which would normally be equal to the index value of the selected entry in the listbox—which will always be a number 0 or higher—is equal to negative one (-1) when no entry in the listbox is selected.  Negative one is NOT a legal index value, so the RemoveAt method generates a critical error when trying to process it.  Stop the program by clicking the Stop button—to the right of the Start Debugging button—on the toolbar:

To make sure the user doesn't crash the program by clicking on the Delete button without selecting an entry in the listbox first, we need to test the value of SelectedIndex prior to using the RemoveAt method, like this:

'Make sure an entry in the lstNames
'    listbox
is selected.
If lstNames.SelectedIndex <> -1 Then
  
'Remove the selected item (SelectedIndex)
    '    from the lstNames listbox
.
   
lstNames.Items.RemoveAt(lstNames.SelectedIndex)
End If

By making sure the value of SelectedIndex is not equal (<>) to -1 prior to using the RemoveAt method, we avoid a program crash.  Use what we did in the btnAdd_Click event procedure and add an Else section here to display an instructive messagebox when the user clicks the Delete button without selecting an entry in the listbox first.

Clearing all items from a ListBox - The Clear button

Take a look through the methods of the Items collection of the lstNames listbox.  Is there a method that clears all the entries from a listbox?  Add this code to the btnClear_Click event procedure:


 

Using a MessageBox to query the User

Messageboxes can be used to get confirmation from the user before doing something that can't be undone (like clearing a listbox with 25,000 entries in it, for example).  Let's improve the code in the btnClear_Click event procedure, so that it looks like this:

'Dimension a DialogResult variable to store
'    the button selection of the user.

Dim iResult As DialogResult
'Display a MessageBox that prompts the
'    user, Yes or No.
iResult = MessageBox.Show( _
        "Sure you want to clear the listbox?"
,  _
        
"Clear Confirmation",  _
        
MessageBoxButtons.YesNo,  _
        
MessageBoxIcon.Question)
'If the user selected the Yes button, clear
'    the listbox.
If iResult = Windows.Forms.DialogResult.Yes Then
    lstNames.
Items.Clear()
End If

By dimensioning the iResult variable as a DialogResult data type (first line of code above), it can capture the return value from the Show method of a MessageBox.  The MessageBox displayed in the above code includes Yes and No buttons (MessageBoxButtons.YesNo).  Once the user clicks a button to close the MessageBox we can examine the iResult variable to determine which button they clicked.  If they clicked the Yes button, we go ahead and clear the listbox.

Making the Delete and Clear buttons user friendly

Are the Delete and Clear buttons easy to use?  When you click on the Delete button does it keep the focus?  Should it?  Test the project so far and make sure it's as easy to use as possible (Hint: Look at the last line of code we added to the btnAdd_Click event procedure).


Part B

Use the following illustration as a guide. It is important that you first place the GroupBox control as shown—Note: find the GroupBox control in the Containers section of the Control Toolbox. Then create the seven CheckBox controls inside the GroupBox.  Use the Text property of the CheckBoxes to set the text next to them. Follow our control naming conventions when naming the CheckBoxes  (Hint: The add checkbox name is chkAdd):

To determine whether a CheckBox is checked or not examine its Checked property like so:

'Is the chkAdd checkbox checked?
If chkAdd.Checked = True Then
     'Hide the btnAdd button
    btnAdd.Visible = False
Else
     'Unhide the btnAdd button
    btnAdd.Visible = True
End If

As you can see in the example code above, you can hide and unhide a Control by setting it's Visible property to True and False respectively.  The above code goes in the chkAdd_CheckChanged event procedure.  Use this example for chkAdd to make all the other checkboxes work.

DO NOT add any enhancements to this project, yet. Project 7 needs this project without additional enhancements.


To copy a Project folder from your Projects folder on the Hard Drive to a floppy diskette or pen-drive follow these steps:

  1. Exit Visual Studio 2010 and insert the floppy diskette or pen-drive, that you want to copy the Project6-7 folder to:
  2. Select the My Documents item on the Start Menu to open the My Documents folder.
  3. In the My Documents folder, double-click the Visual Studio 2010 folder to open it.
  4. Double-click on your Projects folder to open it.
  5. Open the Project6-7 folder by double-clicking on it.  Inside the Project6-7 folder, delete the Obj and Bin folders—these folders are created automatically when you open a project.  You do not need to copy them, or their contents, to your floppy diskette or pen-drive.  Important: Be sure not to delete the My Project folder or Resources folder, if it exists.
  6. Once you have deleted the Obj and Bin folders, hit the Backspace key once—or click the Back button on the toolbar.  This moves you from inside the Project6-7 folder to back inside your Projects folder.
  7. Right-click on the Project6-7 folder and selected: 31/2" Floppy A: or your pen-drive on the Send To fly-out menu.  This copies the Project6-7 folder to your floppy diskette or pen-drive.