Working with Text Box, Label and Command Button
Text box is used to take input from user. User can key in the data into a text box with all editing facilities.
Label control is used to display a static text on the form, such as title.
Command button is used to invoke an action when user clicks on it.
We will develop a simple application to calculate interest with the given amount and rate of interest. See figure 2.1 to get an idea about what we are about to develop in this chapter. The sample application has a single form with the following controls.
- A text box to take amount from user
- A text box to take rate of interest from user
- Two labels to display labels for text boxes
- A label to display calculated interest
- A label to display heading for interest
- A command button to clear the data entered by user
- A command button to calculate interest with the given amount and rate of interest and display the result in label.
- A command button to terminate the form
Figure 2.1: Sample application at run time.
As we have seen in the previous chapter, an application is developed in three different stages; creating user interface, changing properties and writing code for events. So let us first create user interface. But even before that, create a new project.
Creating a new project
As soon as you start Visual Basic IDE, you will be prompted to select the type of project. Once you select the type of project, Visual Basic will create a new project of the selected type. But in some cases you are already in Visual Basic IDE and you want to start a new project.
Let us create a new project for sample application. The following is the procedure to create a new project if you are already in Visual Basic IDE. In case, you are invoking Visual Basic IDE, then Visual Basic will any way create a new project.
To create a new project:
- Select File-> New Project.
- In New Project dialog box, select the Standard EXE as the project type.
- Click on Ok
Visual Basic creates a new project with a single form.
When a new Standard Exe project is created, Visual Basic places a single form in the project with the name Form1. Initially this form will be empty (has no controls on it).
After having created a new project, now move to first step in developing an application – creating user interface.
Creating user interface
Creating user interface involves placing the required controls on the form and arranging them in the required manner. Follow the figure 2.1 while placing controls and arranging them.
You will learn more about aligning controls and changing space between controls in the next chapter. After you have placed all the controls on the form, move to next step i.e., changing properties.
The second step is changing required properties. As we are dealing with new controls, let us first understand what are the new properties we have to deal with.
Text property of the Text box
Text property of the text box represents the text in the text box. It can be used to either change the text in the text box or get the text entered by user in the text box.
Caption property of the Label
This property contains the text that is displayed in the label. Whether the text is completely displayed or not depends on the size of the text, size of the label and AutoSize property of the label. For more details see “Properties of Label control” section later in this chapter.
Each control and form in a Visual Basic project has a name, which is used to refer to the object.
Whenever you access a control in the code, you use the name of the control. Name of the control is set using Name property of the control.
Caption property contains the text to be displayed to the user and Name property contains the name that is to be used in the code to refer to the control.
The name of the control is important because it is used even in the event procedures of the control. The name of the event procedure is formed using the name of the control and the name of the event. For example, if name of the control is cmdQuit and event is Click, then the name of event procedure will be cmdQuit_Click.
Note: The name of the form is not used while forming the names for event procedures related to the form. Instead event procedures of the form contain Form, underscore and then the name of the vent. For example, the name of event procedure of click event is Form_Click.
While giving name to a control, we use a prefix to identify the type of the control. Giving prefix is purely a convention and not a rule in any way. The following is the table shows the standard naming conventions followed in Visual Basic.
|Prefix||Type of control|
|Hsb||Horizontal scroll bar|
|Dir||Directory list box|
|Fil||File list box|
|Drv||Drive list box|
Table 2.1: Standard naming conventions.
We understand various properties. Now let us change the following properties of the control on the form.
|Text||“” (null string)|
|Label2||Caption||Rate of Interest|
After all the properties are changed the form should look like as shown in figure 2.2.
Figure 2.2: Form in design mode after properties are changed.
We will now understand properties related to Font and Alignment properties.
Changing Font related properties
All font related properties are accessed through Font object, which contains a collection of properties related to font.
If you want to change Font related properties for a control, use Font object in Properties Window as follows:
- Select Font property in Properties Window
Properties Window displays three dots (…), which indicate that you can click on dots to invoke a dialog box.
- Click on dots(…) to invoke Font dialog box. Shown in figure 2.3.
- Change necessary attributes of the font such as name, size etc.
- Click on OK
Figure 2.3: Font dialog box used to change font related properties.
Alignment Property for Label and Text Box control
Alignment property specifies how text is to be aligned inside the control. The following are the valid options for Label and Text Box controls.
|VbLeftJustify||0 (Default)||Text is left aligned.|
|VbRightJustify||1||Text is right aligned.|
|VbCenter||2||Text is centered|
Constants are predefined by Visual Basic and internally represent a value. You can use constants instead of using the value that is represented by the constants. Well, we have just completed the second stage of the development. In the next section, we will understand the code to be written.
Writing Code for events
The final step is writing code for events. The following are the events and the action to be taken.
|Click event of cmdClear||Set Text property of txtAmount and txtIntRate to Null string. Set Caption property of lblResult also to null string.|
|Click event of cmdCalculate||Calculate rate of interest and place the result in Caption property of lblResult.|
|Click event of cmdQuit||Terminate the project by unloading the form.|
Table 2.2: Events for which action is to be taken.
Invoke the code window for each command button and write the required code. Code window can be invoked for a control by following the procedure given below.
- Select the control for which you want to write code.
- Double click on the control or Press F7 to invoke code window.
By default Visual Basic displays event procedure for default event. For example, Click event for Command button and Load event for Form.
- If default event procedure is not what you want, then select the required event using events drop down list box.
The following is the code you need to enter for command buttons in the form.
Private Sub CmdClear_Click()
‘ clear text in both the text boxes and lblresult
txtamount.Text = “”
txtintrate.Text = “”
lblresult.Caption = “0”
‘ set focus to txtamount control
Private Sub CmdCalculate_Click()
‘ calculate interst amount and place it lblresult
Dim amount As Single
Dim irate As Single
Dim iamt As Single
amount = CSng(txtamount.Text)
irate = CSng(txtintrate.Text)
‘ calculate: interest = amount * rate /100
iamt = amount * irate / 100
‘ place the result in label control
lblresult.Caption = iamt
Private Sub cmdQuit_Click()
Listing 2.1: Code for Click event of command buttons.
A method is used to perform an operation. A method is always invoked using an object. And the method performs operation on the object that invoked it. SetFocus method is used to set the input focus to the control that invokes it. In our sample application’s code, we used SetFocus method to set input focus to txtAmount control after data is cleared from all the controls.
Save the project as explained using File->Save Project, and run the application to find out whether it is doing what it is supposed to do. Here are the steps to test it.
- Run the application using F5.
- Enter 10000 as the amount in txtAmount text box.
- Press Tab key to move to next text box – txtIntRate.
- Enter 12.5 as the rate of interest.
- Click on Calculate button or press ALT+C.
- At this stage the form should look like the one shown in figure 2.1.
- Click on Clear button or ALT+L to clear the content of the controls.
All values will be cleared from the control.
- You can continue to enter new values or click on Quit button to close the application.
Properties and Events of Text box
The following are the properties and events that are specific to text box control. For all the properties, methods and events please see on-line documentation.
Properties of text box
The following are the properties that are specific to text box. Some of the controls that are related to a particular topic such as data access will not be discussed here and will be discussed with respect to the connected topic.
|Text||Contains the text that is entered into text box.|
|Alignment||Specifies how text is to be aligned in the control. Valid values are 0-left, 1-right and 2-center.|
|HideSelection||Determines whether selected text appears highlighted when focus moves out of control. Default is True, which means selected text is displayed normally when control loses focus.|
|Locked||Specifies whether control can be edited. Default is False.|
|MaxLength||Specifies the maximum number of characters that can be entered into text box. Once this limits is reached the no further input is taken. Default is 0, which means there is no maximum length.|
|MultiLine||Specifies whether user can enter multiple lines into text box or not. Default is False.|
|ScrollBars||Specifies which scrollbars are to be displayed. Valid options are: 0- none, 1-horizontal, 2-vertical and 3-both.|
|PasswordChar||Specifies the character, which is used for display instead of the character entered.|
|Seltext||Contains the text that is currently selected.|
|Selstart and selLength||Specifies the starting position of selection and length of selection.|
Table 2.3: Properties of Texbox
The following are the specific events of the Text box.
Events of text box
The following are the events that are related to text box.
|Event||When is it fired?|
|Change||Whenever either user modifies the text in the text box or text is changed programmatically.|
Table 2.4: Events of the Text box.
To change the caption of a label to the length of the text in text box when ever text is changed:
LblLength.caption = len(txtName.text)
Properties of Label Control
The following are the properties that are specific to label control.
|BackStyle||Specifies whether the background is transparent or opaque. The valid settings are 0 –Transparent and 1 – Opaque (default).|
|BorderStyle||Specifies the type of border to be drawn around label control.|
|AutoSize||Determines whether Label is to be resized to display the entire content. Default is False.|
|WordWrap||Determines whether a Label control with its AutoSize property set to True expands vertically. Otherwise control is expanded horizontally to fit the text specified in its Caption property.|
Table 2.5: Properties of Label control.
Properties of Command Button
The following are the properties that are specific to command button control.
|Cancel||Determines whether the command button is the cancel button of the form. Cancel button of the form is triggered when user presses Esc key in the form.|
|Default||Determines whether the command button is the default button of the form. Default button of the form is triggered when user presses Enter key in the form.|
|Picture||Contains the picture to be displayed on the button.|
|DisabledPicture||Contains the picture that is to be displayed when button is disabled.|
|DownPicuture||Contains the picture that is to be displayed when button is down.|
Table 2.6: Properties of Command button.