More Controls

 

OBJECTIVES:

·       Learn to use additional controls including text boxes, group boxes, check boxes, radio buttons, and picture boxes.

·       Set properties for multiple controls simultaneously.

·       Set tab sequencing for controls.

·       Move and align controls.

·       Write program code to clear the contents of text boxes and labels.

·       Write program code for the WITH and END WITH statements.

·       Concatenate text strings.

·       Set the visible property for controls.

·       Use Tool Tips.

 


INTRODUCTION

Chapter 3 In Class Project

In this chapter you will complete an in-class project that uses numerous controls.  Your will build a project with a form similar to that shown in Figure 3.1 below.  You will learn to use the following new controls:

·       Text Box

·       Group Box

·       Radio Button

·       Check Box

·       Picture Box

Figure 3.1

Text Box Control

In the last chapter you learned to use label controls to display output on a form.  Text box controls can also display output, but the primary purpose of a text box is to enable a system user to enter data onto a form.

 

The form in Figure 3.1 has two text box controls that are accompanied by two label controls.  The label controls display the words "Name:" and "Telephone #:" – these are prompts to tell the system user what type of information is to be typed into the text boxes.

 

Data entered into a text box control is saved to the Text property of the control.  In order to manipulate text box control text contents, you need to assign a meaningful name to each text box control.  You do this by typing a name for the control in the Name property.  The three-character prefix for naming a text box control is txt. 

 

The controls in Figure 3.1 are named txtName and txtTelephone.  Notice that this approach to naming the controls uses the txt prefix along with all or part of the prompt.  Since we will not manipulate the labels that display the prompts, we will not bother naming these labels – we will use their default names of Label1 and Label3.

 

Text box controls have numerous other properties.  You can set their ForeColor and BackColor properties to change the color of text display or the default white background to another color.  The TextAlign property can be set to change the alignment of text from the default of Left to either Right or Center.

 

You can store values to a text box control by using an assignment statement like we did for labels in Chapter 1.  An example assignment statement for the txtName text box is shown here.  Notice that the Text property of a text box is used like the Text property of a label.

 

txtName.Text = "Doug Bock"

 

Group Box Control

A group box control is used to group or contain other controls; thus, this is a type of container control.  We usually group text boxes, radio buttons, and check boxes simply to organize a form so the system user can understand it better.

 

The three-character prefix for naming a group box control is grp; however, we often do not bother to name these controls as we usually do not write any program code to manipulate them. 

 

A group box also has a Text property, and this is used to display the caption at the top of the group box.  For example, Figure 3.1 has three group box controls.  The first one contains the labels and text boxes for Name Information.

 


In-Class Exercise

·       Start VB.NET.  Create a new project.  Give the project an appropriate name (Ch3Example) on the Start Window.  Specify the location for the project depending on whether you're using a floppy disk in Drive A: or a zip disk.

·       Name the form with the form's Name property.  Name it frmCh3Example.

·       Click the Ch3Example VB project name to highlight it in the Solution Explorer window, then open the Project-Properties menu and set the Startup Object value to the form named frmCh3Example.

o      Change the form's Text property to read Chapter 3 Example.

o      Change the form's StartupPosition property to CenterScreen.

·       Add a group box control to store name and telephone information.  Set the Text property of the group box to Name Information.

·       Add two label controls and two text box controls as shown in Figure 3.1.

o      Set the Text property of the label controls to read as shown in the Figure.

o      Set the Text property of the text box controls to be blank (empty).

·       Name the text box controls txtName and txtTelephone, respectively.

·       Save the project and run it.  Attempt to enter data into the text box controls. NOTE: If your project does not build without errors, you probably forgot to set the Startup Object to the form named frmCh3Example. 

·       Terminate the project run.

 


 

Radio Button Control

Radio button controls are used to ensure that the system user can easily select among alternatives.  Use these controls when the system user can select only one of the alternatives.  Figure 3.2 shows a group box control with a Text property value of Color Selected that contains four radio button controls.

Figure 3.2

Each radio button has a Text property that is set to the text value to be displayed – Black, Red, Blue, and Green.

 

The radio buttons are placed on the group box control.  The simplest way to do this is to place the group box control on the form first. 

 

The buttons can be aligned by using the Format menu.  This menu has options to align the controls "left-aligned" and to set both the horizontal and vertical spacing.  In order to align the controls, select the first control by clicking it one time with the left mouse button, then press and hold down either the CTRL or SHIFT key and use the mouse to select the other controls one at a time.  The Format menu can now be accessed to format alignment and spacing for the controls.

 

Notice that the first radio button (Black) is selected by default.  This was done by setting the Checked property of the radio button to True.   If you do not want a radio button selected, the Checked property is set to False.

 

The three-character prefix for naming radio button controls is rad.  Each of the buttons on the project form are named radBlack, radRed, radBlue and radGreen.

 


In-Class Exercise

·       Add a group box control and set the Text property to Color Selected as shown in Figure 3.2.

·       Add the four radio button controls inside the group box control.  Name them appropriately.  Set their Text property values appropriately. 

·       Set the Checked property for the first radio button control to True.

·       Save the project and run it.  Select among the four radio button controls.  You should find that when you select one control, the previously checked control is unchecked.

·       Terminate the project run.

 


 

Check Box Control

Check box controls are similar to radio button controls except that they are used whenever the system user can select zero, one, or more than one of the options presented by check boxes.

 

Figure 3.2 shows a check box with a Text property of Visible or Not.  Check box controls also have a Checked property that stores True or False, depending on whether the check box is checked.

 


In-Class Exercise

·       Add a check box control and set the Text property to Visible or Not as shown in Figure 3.2.

·       Name the check box chkVisible.

·       Save the project and run it.  You should be able to check and uncheck the box.

·       Terminate the project run.

 


 

Picture Box Control

The Picture box control is used to display images on a form.  You display images by first putting the control on the form, then by setting the Image property to the name of a pre-existing graphic file.  The graphic file must have a filename extension of .bmp, .emf, .gif, .ico .jpg, .png, or .wmf.

 

In order to display an image in the control, select the Image property and click the Properties Button as shown in Figure 3.3.  VB.NET will display an Open dialog box where you can browse for the image by filename that you want to assign to the picture box.  The picture is saved to the form's .resx file and becomes a permanent part of the project.

Figure 3.3

Graphics files are available with Visual Basic.NET.  The default folder location is:

 

--Program Files -> Microsoft Visual Studio.NET -> Common7 -> Graphics

 

You can select from the folders listed -- for this in-class project we selected from the Icons folder.  Inside the Icons folder is a folder named Elements.  We placed two picture box controls on the form and stored a snowflake icon to one and a sun icon to the other.

 

Icons are a fixed size.  In order to stretch them to fill the picture box size that you have selected, set the SizeMode property of the picture box control to a value of StretchImage.  You can also make icons appear and disappear by setting the Visible property to True or False by using a program assignment statement at run time.

 

picSnow.Visible = True

picSun.Visible = False

 

The three-character prefix for naming a picture box control is pic.

 


In-Class Exercise

·       Add two picture box controls to your project form. 

·       Name the controls picSun and picSnow. 

·       Set the Image property of each control to display a snowflake in one and an image of the sun in the other.  If you can’t find the image, just download two different pictures off the Internet of use two pieces of clipart.

·       Run your project to confirm that the images display.  Later we will write program code to make the images appear and disappear.

·       Terminate the project run.

 


APPLICATION DESIGN

Adding a Professional Touch

In Chapter 1 you learned about the BorderStyle property.  This property makes controls appear as either flat or three-dimensional.  Controls with a BorderStyle property include labels, text boxes, and picture boxes.

 

The BorderStyle property values are:  (1) None – flat appearance, (2) FixedSingle -- flat appearance with black border, and (3) Fixed3D – three-dimensional, recessed appearance.

 

The text box control default value for BorderStyle is Fixed3D.

 

The label and picture box controls have a default value of None for the BorderStyle property.

Setting the BorderStyle property to an appropriate value can enhance the appearance of a form and generally adds a professional touch to the project.

 

Earlier versions of Visual Basic included shape controls.  VB.NET does not have shape or line controls; however, you can add a line to a form by using a label with the following property settings:

·       Text property – set to blank.

·       BorderStyle – set to None.

·       BackColor – set to the desired color.

·       Line size – set with the Width and Height properties.

 

Working More Productively

Often you will build forms that have several controls of the same type, for example, several buttons or check boxes or labels.  You can work more productively by learning to select and work with more than one control at a time.  Selecting more than one control at a time will enable you to set properties that they have in common, such as the BorderStyle for all controls at one time.  This will also enable you to align controls on a form more rapidly.

 

One way to select more than one control at a time is to use the lasso method.  If the controls are located on a form near to each other, simply place the mouse pointer at one corner of an imaginary box around the controls, hold down the left mouse button and drag the mouse toward the opposite corner.  You'll notice that a "dashed line" selection box forms around the controls, and when you release the mouse button, each selected control will be highlighted with selection handles like those shown around the buttons in Figure 3.4.

Figure 3.4

 

Another way to select more than one control at a time is to click on one control and while holding down either the shift or control key, click the other controls that you wish to select.  This approach works best when selecting controls that are not next to one another or controls located inside a group box control.

Still another way is to use the Edit menu, Select All option.

 

To "unselect" a group of controls, click away from the controls someplace on the form.

 

You can move all controls selected as a group by dragging them with the mouse button.

 

You can set properties of multiple controls that are common properties.  For example, you can select the three command buttons on our in-class exercise form and set the BackColor property to red for all three buttons at the same time.  This is faster than setting them one at a time.

 

You can align and resize controls by using the buttons on the Layout Toolbar shown in Figure 3.5.   If this toolbar is not visible, select the View menu, Toolbar option and select the Layout Toolbar.  The toolbar buttons are disabled (grayed out) until you select more than one control.  Practice with this tool bar now.

Figure 3.5

User Interface Features

The form you design should be easy to use.  The more intuitive the form is in terms of system user's understanding how to use it, the less training that will be required to teach system users how to be productive with the computer applications that you program.  Follow these guidelines.

 

        Color

 

Use predominantly gray colors to avoid problems for people who are color blind.

 

Use white backgrounds for text boxes and gray backgrounds for labels.  This will keep system users from trying to type data into labels where data cannot be entered and will make it obvious which area on a form can be used for data entry.

 

Grouping

 

Use group boxes to group controls to aid the system user in organizing how information on a form is presented and is to be used.

 

If labels display messages such as prompts to enter data into an accompanying textbox, leave the labels with a flat BorderStyle property. 

 

If labels will display output from some type of process, use a BorderStyle of either FixedSingle or Fixed3D.

 

Fonts

 

Use a MS Sans Serif font for most information on a form as this font is easiest for most people to read.

 

Do not use large fonts except for a limited number of items.

 

Do not use bold fonts except to highlight select information.

 

Keyboard Access Keys

 

Some people prefer to use a keyboard instead of a mouse when using a system.  Always define keyboard access keys (hot keys) for buttons.  In Figure 3.4 you saw the Text values displayed on buttons with one letter (hot key) underlined.  This is accomplished by typing an ampersand (&) just before the hot key character in the Text property of the button.  For example, to display Exit, type E&xit – this will make the Alt-X key combination the hot keys for the Exit button.

 

When defining hot keys, use the Microsoft Windows standard that you'll find used on the menus of Microsoft software products such as VB.NET.

 

Avoid defining the same hot key for more than one control.

 

Sometimes, with Windows 2000 and XP, the underline will not appear on a control until you press the Alt key to initiate the use of the hot keys.

 

Setting a form's AcceptButton and CancelButton Properties

 

You can make the keyboard Enter key act like the click event for one of the buttons (or other controls) on a form by setting the form's AcceptButton property to the name of the button you wish to activate when the Enter key is pressed.  For example, set the form's AcceptButton property to btnDisplay for the in-class project to map this button to the Enter key.

 

You can make the keyboard ESC key act like the click event for a different button (or other control) on a form by setting the form's CancelButton property to the name of the button you wish to activate when the ESC key is pressed.  For example, set the form's CancelButton property to btnClear for the in-class project to map this button to the ESC key. 

 

Tab Order

 

When the Tab key is pressed, the "focus" or blinking cursor should tab from one control to the next in left to right, top to bottom order. 

 

You can control the tab order by setting each control's TabIndex property.  Simply number the controls 0, 1, 2, 3, etc in the order by which you wish to tab to the controls.

 

Alternatively, you can use the View menu, Tab Order option to display the tab order.  Clicking the controls one at a time will change the tab order to the order by which you click the controls.  Turn off the tab order display by again selecting the View menu, Tab Order option.

 

The tab order for controls such as radio buttons inside a group box is not controlled at run time by the tab key.  Rather, you must tab to the group box then use the keyboard up and down arrow keys to select among the radio buttons.

 

Form's StartPosition Property

 

Usually system users will want a form to display in the center of the screen when only one form is visible at a time.  You can control this by setting the form's StartPosition property to the CenterScreen value. 

 

Tool Tips

 

Tool tips are those little labels that display whenever a system user pauses the mouse pointer over a toolbar button or a form control.

 

Tool tips are added by using the ToolTip control.  Add this control to the form by selecting it from the toolbox and clicking anywhere on the form (See Figure 3.6). 

 

Figure 3.6

 

The ToolTip control will be displayed in the component tray that is used to store controls that are not visible at run time (see Figure 3.7)

 

Figure 3.7

 

After you add a ToolTip control to a form, each control on the form will have a new property.  Here the property will be named ToolTip on ToolTip1 (if you don't change the name of the ToolTip control.  You can type the text to be displayed as a tip for the control into the ToolTip on ToolTip1 property for those controls that need tips.

 


In-Class Exercise

·       Use the Layout Toolbar to align all controls on the form that might not be aligned properly.

·       Set the form's AcceptButton and CancelButton properties to map the btnDisplay button to the Enter key and the btnClear button to the ESC key.

·       Select all three buttons at the same time – set the BackColor property of all three buttons to light blue.

·       Define hot keys for the three buttons as shown in Figure 3.1.

·       Check the tab order of the controls on your project.  Ensure that they tab from top to bottom, left to right.

·       Add a ToolTip control to the project.  Add appropriate tip messages for both of the text boxes and all three of the buttons.

·       Run your project to check that the modification you made appear properly during project execution.

·       Terminate the project run.

 


PROGRAM CODING

Clearing Text Box and Label Contents

In Chapter 1 you learned the assignment statement.  In order to clear the contents displayed in either a textbox or label, you must assign a value of the empty string to the Text property of these controls.  The empty string is denoted by typing a set of two double-quote marks together with no space between them.  Example:

 

txtName.Text = ""

lblMessage.Text = ""

 

Alternatively, you can clear a text box by using the Clear method.  Example:

 

txtName.Clear()

 

Setting the Focus

If you wish to set the focus of the cursor to a specific control, such as the first textbox on a form, you use the Focus method.   Example:

 

txtName.Focus()

 

Selecting and Unselecting Radio Buttons and Check Boxes

You can select and unselect these controls in program code by setting the Checked property to either True (to select) or False (to unselect).  Examples:

 

radBlack.Checked = True

radBlue.Checked = False

chkVisible.Checked = True

 

Making a Picture Box Control Visible or Invisible

Figure 3.8 shows part of the in-class exercise project form.  Earlier we placed two picture box controls on this form and named them picSun and picSnow.

Figure 3.8

You will now learn how to code a Click event for each of these picture box controls in order to create a special graphics effect – sun turning to snow and back to sun again whenever one of the images is clicked.

 

A picture box control image can be made visible or invisible by setting the Visible property to either True or False, respectively.  This can be done by setting the Visible property within the Properties Window.  It can also be done in programming code as is shown here. 

 

picSnow.Visible = True

picSun.Visible = False

 

This code would be placed inside a Click event procedure for a picture box control as is shown here. 

 

'Project: Chap2Example

'D. Bock

'5/18/2002

'

Public Class frmCh3Example

    Inherits System.Windows.Forms.Form

 

#Region " Windows Form Designer generated code "

 

#End Region

 

Private Sub picSun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picSun.Click

    'Make the Snow image visible and the Sun image invisible

    picSnow.Visible = True

    picSun.Visible = False

End Sub

End Class


In-Class Exercise

·       Set the Visible property of picSnow to False.  Set the Visible property of picSun to True.

·       Drag the image of the Sun over the top of the Snow image.

·       Write code for the Click event of the picSun picture box control as shown above.  You can access the Click event by double-clicking the picSun picture box control.

·       Write code for the Click event of the picSnow picture box control.  Hint:  The code should make the Snow image invisible and the Sun image visible – the opposite of the code for the picSun_Click event.  You can access the Click event for picSnow from the coding window by selecting the picSnow object and Click events as shown in Figure 2-9 below.

Figure 3.9

·       Run your application and test it by clicking on the picture box control images.

·       Terminate the project run.

 


Changing Textbox and Label ForeColor and BackColor Properties

As you have seen already, many properties can be set/changed either through the Properties Window or by writing program code. 

 

Text box and label controls have color properties that sometimes need to be modified to meet system user requirements.  The ForeColor property sets the color of text displayed in these controls.  The BackColor property sets the background color of text boxes and labels.

 

You've already seen how to set these properties through the Color Palette selection window.  You can set these properties in program code as shown in the examples here:

 

txtName.ForeColor = Color.Green

lblMessage.BackColor = Color.Blue

 

As you type the program code, VB.NET will display popup selection windows to guide you in selecting from available, predefined colors as is shown in Figure 3.10.  The popup selection window displays whenever you type the period (dot) after the VB reserved word Color.

Figure 3.10

 

The WITH and END WITH Statements

If you need to set several properties for an individual control, you can use the With and End With statements to shorten the coding, and to make your code earlier.  Additionally, programs written in this fashion with these With blocks will execute a little bit faster than those that do not use this approach.

 

The code shown here will make the txtName text box control visible, set the text colors for foreground and background, and set the focus to this control.

 

With txtName

    .Visible = True

    .ForeColor = Color.Black

    .BackColor = Color.White

    .Focus()

End With

 

You'll notice that the code inside the With block is indented four spaces.  This is normal coding procedure to make the code easier to read.

 

Concatenating Text Properties and Continuing Lines

Sometimes you will need to display text typed into a text box control to a label control.  This is easily accomplished with an assignment statement like the one shown here.  This code would be placed inside a Click event for a button control.

 

lblMessage.Text = txtName.Text

 

However, you may sometimes need to display information from two or more text box controls to a single label.  This requires you to concatenate (combine) the information from both controls by using the concatenation operator which is the ampersand (&).  Suppose that you wish to display the name and telephone number from the textboxes of your in-class exercise to the label named lblMessage.  The code would look like this:

 

lblMessage.Text = txtName.Text & txtTelephone.Text

 

You can also concatenate strings of characters as part of a concatenation display operation.  Example:

 

lblMessage.Text = "Name is: " & txtName.Text _

    & "  Telephone Number is: " & txtTelephone.Text

 

The above coding example also demonstrates use of the line continuation character – the underscore preceded by a blank space.  VB.NET treats these two coding lines as a single line of code.  This is useful whenever a coding line is long and will not fit onto the computer screen – this makes it easier to read the code.

You'll also notice that we indented the continued line 4 spaces.  This is normal coding procedure to make the code easier to read.

Coding the Display and Clear Buttons

Now you've learned enough to write code for the Click events for the btnDisplay and btnClear controls.  Complete the in-class coding exercise described below.

 


In-Class Exercise

·       Access the btnDisplay control's Click event in the coding window (hint: double-click the btnDisplay button on the form).

·       Write code to display the name and telephone number that are typed in the text box controls whenever btnDisplay is clicked.  Display the text values using a Blue foreground color.

·       Access the btnClear control's Click event.  Write code to:

o      Clear the contents of the label named lblMessage.

o      Clear the contents of both text box controls (txtName and txtTelephone).

o      Set the Color Selected radio button to the radio button labeled Black (radBlack control's Checked property).

o      Unselect the check box labeled Visible or Not.

o      Set the focus to the txtName control.

·       Run your project and test the operation of these two buttons.  You should also confirm that the Enter key is mapped to the btnDisplay control and the ESC key is mapped to the btnClear control.

·       Terminate the project run.

 


Coding a Radio Button's CheckChanged Event

When you click a radio button control, the control does not exhibit a Click event – rather, it exhibits an event named CheckChanged. 

 

You can write code for the four radio buttons shown on the in-class project form to execute whenever one of the radio buttons is clicked.  In this example, when the radio button with a Text property of Black is clicked, the ForeColor property of the text displayed in the label named lblMessage is changed to the color black.

 

Private Sub radBlack_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radBlack.CheckedChanged

    'Make Label Text Black

    lblMessage.ForeColor = Color.Black

End Sub

 


In-Class Exercise

·       Access the CheckChanged event for each of the radio buttons that are used to select a color.  Set the ForeColor property of the lblMessage control to the color indicated by the radio button.

·       Enter text into the text boxes, click the Display button, then select a color radio button.  Ensure that the text color changes for each radio button.

·       Terminate the project run.


Coding the Exit Button

Recall from Chapter 1 that in order to exit a program by clicking a button control (the btnExit control), you close the form.  The following code will close the form.

 

Me.Close()

 


In-Class Exercise

·       Finish the in-class exercise by writing code to close the form when the btnExit control is clicked.

·       Run the project and test the btnExit_Click event code.

·       Terminate the project run.

 


 

Solution to In-Class Exercise

 

'Project: Chap2Example

'D. Bock

'9/4/2003

'

Public Class frmCh3Example

    Inherits System.Windows.Forms.Form

 

#Region " Windows Form Designer generated code "

 

#End Region

 

    Private Sub picSun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picSun.Click

        'Make the Snow image visible and the Sun image invisible

        picSnow.Visible = True

        picSun.Visible = False

    End Sub

 

    Private Sub picSnow_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles picSnow.Click

        'Make the Sun image visible and the Snow image invisible

        picSnow.Visible = False

        picSun.Visible = True

 

    End Sub

 

    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click

        'Display name and telephone number to lblMessage control.

        lblMessage.Text = "Name is: " & txtName.Text _

            & "  Telephone Number is: " & txtTelephone.Text

    End Sub

 

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

        'Clear labels, textboxes, reset radio buttons and check boxes.

        'Set the focus to the Name text box.

        lblMessage.Text = ""

        txtName.Clear()

        txtTelephone.Clear()

        radBlack.Checked = True

        chkVisible.Checked = False

        txtName.Focus()

    End Sub

 

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click

        'Close the form

        Me.Close()

    End Sub

 

    Private Sub radBlack_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radBlack.CheckedChanged

        'Make Label Text Black

        lblMessage.ForeColor = Color.Black

    End Sub

 

    Private Sub radRed_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radRed.CheckedChanged

        'Make Label Text Red

        lblMessage.ForeColor = Color.Red

    End Sub

 

    Private Sub radBlue_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radBlue.CheckedChanged

        'Make Label Text Blue

        lblMessage.ForeColor = Color.Blue

    End Sub

 

    Private Sub radGreen_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radGreen.CheckedChanged

        'Make Label Text Green

        lblMessage.ForeColor = Color.Green

    End Sub

 

    Private Sub chkVisible_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkVisible.CheckedChanged

        'Make Label visible or invisible

        'If Checked property of checkbox is true,

        'then label is visible.

        'If Checked property of checkbox is false,

        'then label is invisible.

        lblMessage.Visible = chkVisible.Checked

    End Sub

End Class

 

End of Notes.