Wednesday, February 19, 2020

Chapter 1 Introduction To Visual Basic










Introduction to Interface/Components

There are several interface components that have come be a part and parcel of graphical user interface.  They are made up of components like buttons, list boxes, menus and windows.

Visual Basic Application Window The window

The wi  After creation of window other controls may be positioned in it.  Window is also referred as form.
ndow is the container where interfaces are placed together.

VB Properties WindowWindow properties

Properties are used to govern appearance and behavior of a window.  Window properties are:

1)    Caption/title Text used to name of the application and its action in
progress.
2)     Width and Height it decides size of the window.
3)  Top and Left used to determine location of the window in the screen.
4)      Resizable it decides whether window can be resized at runtime.

Window Methods
Open used to open a window.
Visual Basic Tool Box 
Move used to move window to a new position.

Print used to print the window.
                                                                                                   
Window events
Click Occurs when user clicks on a window.
Resize Occurs when user resizes the window. 
                                 
Command Button Command button
Referred also as a push button, used to initialize an action.

Command button properties
Caption Text displayed on the command button, used to indicate action of the button.
Default It ensures that the press of enter key will mean the same as clicking on it.
Cancel It ensures that the press of Esc key will mean same as clicking on this button.

                                                                                                         Visual Basic Tool Box à
Command button Methods
Methods are used to manipulate a command button at run time.
Move Used to move a button during course of execution of the program.
Set Focus Used to make the command button the current active element in window.

Command button Events
Click Occurs when user clicks on it.
KeyPress Occurs when command button is current selected element and a key is pressed on the keyboard.
GetFocus Occuras when command button is made the current active element.

Text BoxText Box
It is a control that is used to accept information from the user.

The text box properties
Text Used to read or to set text in text box.
Max length Used to set maximum number of characters to be entered in the text box.  There is no default value placing restriction on text is possible.
Multiline Setting this property enables the user to enter multiple lines of the text.

Text box Methods
Clear Clears contents of the text box at the run time.
Copy Copies contents of the text box to clip board at the run time.

Text box Events
KeyPress This event is called each time a key is pressed with the focus is on the text box.
Change occurs each time the contents of the text box are changed.

Label The Label
It is a control used to place text in a window.  It is used to identify controls that do not have a caption property of their own.

The label properties
Caption This holds the text to be displayed by the control.  It can be used in the code of an application to change the text displayed by the label.
Word wrap When this property is set to false, it will ensure that text of label is displayed as a single line.

Label Methods
Move Used to move the label at run time.
Size  Used to size the label at run time.

Label Events
Click Occurs when user clicks on label.
Change Occurs when text of a label is changed by the application.
Double Click Occurs when user double clicks on the label.

List Box List Box
List boxes are used to present list of available options. The user selects one or more items by clicking on required item are displayed list.

List Box Properties
List index Is a number used to access individual elements in list box.  List box index starts from 0 for first item in list box and takes on consecutive numbers for following elements.
Sorted Used to display items in sorted order.
Multiple selection Used to specify if the user can select multiple items in the list.

List box Methods

Add Item Will add specified item to the list box.  New item is appended to end of list.
Remove Item Used to delete an item from the list.
Selected Item Used to obtain current selected item in the list.

List Box Events
Click Occurs when user clicks on the list box.
Scroll Occurs when user scrolls through the list in the list box.

Combo Box Combo box or drop down list box
Combo box is a combination of a list box and text control.  List box allows user to only select from available list by clicking on it.  It is not allowed to key-in a value.

Combo box properties

Style Value assigned to this property decides ‘look’ of the combo box.
Locked Used to specify whether combo box should have its list displayed or hidden.  Or user can enter a value in the text box selection of the control.
A combo box allows the user to select only one item at a run time.

Combo box methods
Add Item This will add specified item to the list box.  New item is appended to the end of the list.
Remove Item Used to delete an item from the list.

Combo box Events
Click Occurs when user clicks on it during run time.
Scroll Occurs when user scrolls through list in the list box during run time.
Change Occurs when user changes text in the text box portion of the combo box during run time
Drop down Occurs when user clicks on the arrow to display the list during run time.

Radio Button Radio button or option button
Radio or option buttons are used when user wants to select only one of multiple options during run time.

Radio button properties

Caption Text that appears next to radio button.
Value It specifies whether Radio button is selected.

Radio button methods

Move Occurs when user moves the radio button on the form.
Resize Occurs when user resizes the radio button.

Radio button events

Click Occurs when user clicks on it.

Check box
Check box control is used when a user wants to select multiple options from the given options.  User can select as many check boxes as required.  The check box, when selected displays the ü symbol.

Check box properties

Caption Text that appears next to check box.
Value This Property specifies which check box is selected

Check box methods

Move Occurs when check box is moved.
Resize Occurs when a check box is resized.

Check box events
 Click Occurs when user clicks on the check box.

Group box or frame
Group BoxWhen multiple radio buttons are placed directly in a window, to display a particular group items; we have to place a frame to indicate that it resembles a particular group. And user can select only one of them.
First group box is placed in window and then radio buttons, check box (or any control) that are to be a part of a group are placed within this frame.  Each group of radio buttons has its own frame.

Group box properties
Caption Name of the group box or frame.

Group box methods
Move Used to move the frame.

Group box events
Click Occurs when user clicks on the frame.
Double click Occurs when user double clicks on the frame.

Image Image
Image control is used to place picture in the user interface.

Image properties

Picture Specifies name of the picture file.
Stretch It indicates whether the picture is to be resized to fit the size of the image.

Image methods

Move Occurs when Picture (Image) is moved.

Size Occurs when an Image is resized.

Image events
Click Occurs when User clicks on an image.

The graphic controls
Graphic Controls Line
Circle
Rectangle
These are meant to enhance look of the interface and have no events associated with them.

Graphic control properties

Line width Sets the line width.
Line style Decides Style of the line.
Line color Sets color of the line
Fill color Used to fill color inside the Shape.


Graphic control methods

Move Occurs when User Moves the Graphic control.

Data and data types
The important data types supported by the programming tools are:-

Numeric Numbers of any type constitute numeric data.  The numbers may be real or whole.  Numeric data can contain
Ø  Only numeric characters of 0 to 9.
Ø  The decimal point.

Numeric data can be subjected to mathematical operations.

Alphanumeric This can be made up of any type of characters.
Ø  Numbers 0 – 9.
Ø  Alphabetic A to Z or a to z.
Ø  Special characters #, $, * etc.

Data that is descriptive as Name, Address etc. falls in this category.
Alphanumeric data is generally enclosed within quotes.

Date and time Are special data types all to themselves.  As:-
Ø  Day
Ø  Month
Ø  Year,  and
Ø  Hour
Ø  Minute
Ø  Second

Logical Can have only two value.
Ø  True
Ø  False

Special types This includes
Ø  Large amount of text
Ø  Sound
Ø  Movie
Many times such special types of data need to be stored for future use.

Variables
When an application is to be handled data it needs some place where it can temporarily stores this data.  This ‘place’ is called as memory.  Variables can be assigned different values during life time of the application.

Constants
Refers to data that remains unchanged during the course of execution of application. 
For example : Num1 = 12

Where 12 is the constant and it is stored in the variable ‘Num1’

Files
Data has to be stored in a permanent format that it can be recalled at any time when required.  This stored data is called a file.  The data written into a file maintains the data structure.  This allows the data to be reconstituted exactly as it was.
A table with all its records should be saved such that the structure is maintained and table can be recalled at a later stage.

Data bases
When a table is written to a file it must be done the way that table can be reconstituted at any time in the future.  The table holds following information:-
Ø  Table name
Ø  Column information
o   Names
o   Data type       
Ø  Actual data
o   Records

Validations
Means verifying the data confirms to certain conditions.  It performs important part in an application.

Need for validations
Validations are performed to ensure that only correct data is stored to the database.  If data is not validated then it is quite possible that erroneous data is stored and this data when used in other calculations will lead to more errors.

In following pay slip application validations could be implemented as:-
  1. Name is always alphabetic data.
  2. Grades can either ‘1’ or ‘2’ and not other value.
  3. Basic can numeric only and between 2000/- and 10000/-.
  4. Neither of fields can be left empty.
  5. Dates are to follow mm/dd/yy format.
  6. Code should start with Alphabet and the number.
All this will prevent the user from entering a wrong data

 Pay Slip Application Window

Payslip Application





Top



Practical Session 1

Example 1 Code For Adding Two Numbers 

Adding Two NumbersDesign the Form As follows:- Place Two Labels for Indicating the Values of Text Boxes, Two Text Boxes Text1 and Text2 and place three Command Buttons For Add, Average and Exit.

This Application will accept two numbers from you and gives the Sum and Average by Clicking that Individual Buttons.  Exit button is used to Exit From the Application and control is transferred to Visual Basic Design View.  The Result is displayed in the Message Box.

Write Following Codes for Individual Buttons as follows:
Private Sub Command1_Click( )
MsgBox "the Sum is " & Val(Text1.Text) + Val(Text2.Text)

Private Sub Command2_Click( )
MsgBox "the Sum is " & Val(Text1.Text) + Val(Text2.Text)/2 End Sub

Private Sub Command3_Click( )
Unload Me
End Sub

Example 2

The Code for the above Application can also be written with the help of using Functions.  Hence modify the code as follows:-

Functions are explicitly called with the Keyword Call and the Function name.  For example Call disp_res (For Displaying the Result of the functions). 

There are two other functions are also defined in the application they are add_nums (For addition of two numbers)and avg_nums (For calculating the Average of two numbers).  The keyword dim is used to define the variable name and its data type used in an application.
Private Sub Command1_Click( )
Dim sum As Double
Sum = add_nums(Text1.Text, Text2.Text)
Call disp_res("this is the Sum", sum)
End Sub
Function add_nums(num1 As Double, num2 As Double) As Double
Dim result_add As Double
result_add = num1 + num2
add_nums = result_add
End Function
Function avg_nums(num11 As Double, num12 As Double) As Double
Dim result_avg As Double
result_avg = add_nums(num11, num12) / 2
avg_nums = result_avg
End Function

Sub disp_res(title As String, disp_num As Double)
Dim res As Integer
res = MsgBox(disp_num, vbOKOnly, title)
End Sub

Private Sub Command2_Click( )
Dim average As Double
average = avg_nums(Text1.Text, Text2.Text)
Call disp_res("This Is The Average", average)
End Sub

Private Sub Command3_Click( )
Unload Me
End Sub

Example 3
Design the Form as Follows: Place Three Label Boxes, Three Text Boxes and four Command Buttons.  Write the Code for the command button’s Click Events as under:-

Accepting Numbers

In the General Declaration we declared two global variables nums (1 to 20) and idx.

Dim nums (1 To 20) As Integer
Dim idx As Integer

For the Command1’s Click event the index is assigned to second text box and that is incremented by 1.
Private Sub command1_Click( )
nums(idx) = Text2.Text
idx = idx + 1
If idx > Text1.Text Then
Command1.Enabled = False
Command2.Enabled = True
Else
Text2.Text = ""
Text2.SetFocus
End If
End Sub

Private Sub Command2_Click( )
Command1.Enabled = False
Command2.Enabled = False
Command3.Enabled = False
Text1.Text = ""
Text1.Enabled = True
Text1.SetFocus
Text2.Text = ""
Text3.Text = ""
idx = 1
End Sub

Private Sub Command3_Click( )
Dim sum, counter As Integer
sum = 0
For counter = 1 To Text1.Text
sum = sum + nums(counter)
Next
Text3.Text = sum
Command3.Enabled = True
End Sub

Private Sub Command4_Click( )
Unload Me
End Sub
Private Sub Form_Load( )
idx = 1
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End Sub

Private Sub Text1_LostFocus( )
Dim result As Integer
If (Text1.Text < 2) Or (Text1.Text > 20) Then
result = MsgBox("Please Enter a Number Between 2 and 20)", vbOKOnly, "Stop")
Text1.Text = ""
Text1.SetFocus
Else
Text1.Enabled = False
Command1.Enabled = True
Command4.Enabled = True
End If
End Sub

Example 4(Calculating Time Between Start and End Time).
Calculate Time Between Start and End Time
In The General Declaration
Option Explicit
Dim StartTime As Variant
Dim EndTime As Variant
Dim ElapsedTime As Variant

Private Sub cmdEnd_Click( )
EndTime = Now
ElapsedTime = EndTime - StartTime
lblEnd.Caption = Format(EndTime, "hh:mm:ss")
lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub
Private Sub cmdExit_Click( )
End
End Sub
Private Sub cmdStart_Click( )
StartTime = Now
lblStart.Caption = Format(StartTime, "hh:mm:ss")
lblEnd.Caption = ""
lblElapsed.Caption = ""
End Sub



Top

No comments:

Post a Comment