Introduction To Visual Basic 6 - 1-To-10Chapter
Introduction To Visual Basic 6 - 1-To-10Chapter
Getting started
To open the Visual Basic environment and to work with it select and click on Microsoft Visual Basic 6.0 in the start menu. When Visual Basic is loaded the New Project dialog shown in figure 1.1 will be displayed with the types available in Visual Basic. You can notice that Standard Exe is highlighted by default. Standard Exe allows the user to create standard executable. Standard executable is a type which has most of the common features of Visual basic. Figure 1 The Visual Basic startup dialog box
The window titled Project -Project 1 is called the project explorer which contains the project files Property window displays the properties of a form or a control. Properties are attributes such as size, name etc. as well as the form all the controls have its own set of properties Toolbox window contains a set of controls which are used to customize forms. Using this controls user can create an interface between user and the application Figure 3 Toolbox window with its controls available commonly.
Description used to interact with the controls on the form used to display images used to accept user input which can display only editable text used to group other controls
CheckBox OptionButton ListBox ComboBox HScrollBar VScrollBar Timer DriveListBox DirListBox FileListBox Shape Line Image Data OLE Label
used to do a choice for user (checked or unchecked) used in groups where one at a time can be true used to provide a list of items used to provide a short list of items a horizontal scrollbar a vertical scrollbar used to perform tasks in specified intervals. used to access to the system drives used to access to the directories on the system used to access to the files in the directory used to draw circles, rectangles, squares, ellipses used to draw lines used to display images. But less capability than the PictureBox used to connect a database used to interact with other windows applications used to display texts which cannot be edited
Chapter 2
* May be as much as 255 characters long (but don't forget that somebody has to type the stuff!). * Must not contain a space or an embedded period or type-declaration characters used to specify a data type; these are ! # % $ & @ * Must not be a reserved word (that is part of the code, like Option, for example) * The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of First-name use First_name or FirstName.
Variables
Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255 characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or $. There are two types of declarations 1. Explicit declaration
2. Implicit Declaration Scope of variables A variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared. The scope of a variable, procedure or object determines which part of the code in our application are aware of the variable's existence. A variable is declared in general declaration section of e Form, and hence is available to all the procedures. Local variables are recognized only in the procedure in which they are declared. They can be declared with Dim and Static keywords. Local Variables A local variable is one that is declared inside a procedure. This variable is only available to the code inside the procedure and can be declared using the Dim statements as given below.
e.g.: Dim sum As Integer
Static Variables Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains or preserves value even when a procedure ends. A static variable is declared as given below.
e.g.: Static tot As Integer
Module level Variables A module level variable is available to all the procedures in the module. They are declared using the Public or the Private keyword.
e.g.: Public ans As Integer Private Temp As Integer
Procedures
Sub Procedures A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)] [ statements] End Sub
Event Procedures An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load() ....statement block End Sub
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a good programming practice to write common statements in a separate procedure (general procedure) and then call them in the event procedure.. Function Procedures Functions are like sub procedures, except they return a value to the calling procedure. They areespecially useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then the functions returns a value that indicates the results of the tasks complete within the function. The following function procedure calculates the third side or hypotenuse of a right triangle, where A and B are the other two sides. It takes two arguments A and B (of data type Double) and finally returns the results.
Function Hypotenuse (A As Double, B As Double) As Double Hypotenuse = sqr (A^2 + B^2) End Function
Property Procedures A property procedure is used to create and manipulate custom properties. It is used to create read only properties for Forms, Standard modules and Class modules. Visual Basic provides three kind of property procedures-Property Let procedure that sets the value of a property, Property Get procedure that returns the value of a property, and Property Set procedure that sets the references to an object.
Relational Operators Operators > < Description Greater than Less than 10>8 10>8 Example True False Result
Greater than or equal to 20>=10 Less than or equal to Not Equal to Equal to 10<=20 5<>4 5=7
Logical Operators Operators OR AND Description Operation will be true if either of the operands is true Operation will be true only if both the operands are true
Chapter 3
If <condition> Then statement End If e.g.: If average>75 Then txtGrade.Text = "A" End If
Method 2
If < condition 1 > Then statements Else If < condition 2 > Then statements Else If < condition 3 > Then statements Else Statements
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then txtGrade.Text = "A" ElseIf average > 65 Then txtGrade.Text = "B" ElseIf average > 55 Then txtGrade.text = "C" ElseIf average > 45 Then txtGrade.Text = "S" Else txtGrade.Text = "F" End If
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer average = txtAverage.Text Select Case average Case 100 To 75 txtGrade.Text ="A" Case 74 To 65 txtGrade.Text ="B" Case 64 To 55 txtGrade.Text ="C" Case 54 To 45 txtGrade.Text ="S" Case 44 To 0 txtGrade.Text ="F" Case Else MsgBox "Invalid average marks" End Select
Note: In this example I have used a message box function. In later lessons you will learn how to use message box functions.
Chapter 4
Dim number As Integer number = 1 Do While number <= 100 number = number + 1 Loop
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.
The programs executes the statements between Do and Loop While structure in any case. Then it determines whether the counter is less than 501. If so, the program again executes the statements between Do and Loop While else exits the Loop.
Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop structure tests a condition for falsity. Statements in the body of a Do Until...Loop are executed repeatedly as long as the loop-continuation test evaluates to False. An example for Do Until...Loop statement. The coding is typed inside the click event of the command button
Dim number As Long number=0 Do Until number > 1000 number = number + 1 Print number Loop
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.
The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition structure handles all the details of counter-controlled repetition. The following loop counts the numbers from 1 to 100:
Dim x As Integer For x = 1 To 50 Print x Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2 Print x Next
The following loop counts numbers as 1, 3, 5, 7..etc The above coding will display numbers vertically on the form. In order to display numbers horizontally the following method can be used.
For x = 1 To 50 Print x & Space$ (2); Next
To increase the space between the numbers increase the value inside the brackets after the & Space$. Following example is a For...Next repetition structure which is with the If condition used.
Dim number As Integer For number = 1 To 10 If number = 4 Then Print "This is number 4" Else Print number End If Next
In the output instead of number 4 you will get the "This is number 4".
Chapter 5
The preceding code increments the value of x by 1 until it reaches the condition x = 5. The Exit For statement is executed and it terminates the For...Next loop. The Following statement block containing Do...While loop is terminated using Exit Do statement.
Dim x As Integer Do While x < 10 Print x x = x + 1 If x = 5 Then Print "The program is exited at x=5" Exit Do End If Loop
In the above coding, the object Text1, which is a text box is evaluated only once instead of every associated property or method. This makes the coding simpler and efficient.
Chapter 6
types including variant, user-defined types and object variables. The individual elements of an array are all of the same data type.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of elements required by the array so that the compiler may reserve the appropriate amount of memory. Arrays may be declared as Public (in a code module), module or local. Module arrays are declared in the general declarations using keyword Dim or Private. Local arrays are declared in a procedure using Dim or Static. Array must be declared explicitly with keyword "As". There are two types of arrays in Visual Basic namely: Fixed-size array : The size of array always remains the same-size doesn't change during the program execution. Dynamic array : The size of the array can be changed at the run time- size changes during the program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit should always be within the range of long data type. Declaring a fixed-array
Dim numbers(5) As Integer
In the above illustration, numbers is the name of the array, and the number 6 included in the parentheses is the upper limit of the array. The above declaration creates an array with 6 elements, with index numbers running from 0 to 5. If we want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6. A public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indexes: The first (by convention) identifies the element's row and the second (by convention) identifies the element's column. Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. Note that multidimensional arrays can have more than two dimensions. Visual Basic supports at least 60 array dimensions, but most people will need to use more than two or three dimensional-arrays.
It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. An example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
Dynamic Arrays
There will be a situation when the user may not know the exact size of the array at design time. Under such circumstances, a dynamic array can be initially declared and can add elements when needed instead of declaring the size of the array at design time. Dynamic arrays are more flexible than fixed-arrays, because they can be resized anytime to accommodate new data. Like fixed-sized arrays, dynamic arrays have either Public (in code modules), module or local scope. Module dynamic arrays are declared using keyword Dim or Private. Local dynamic arrays are declared with either Dim or Static.
e.g.: Dim dynArray ( )
The actual number of elements can be allocated using a ReDim statement. This example allocates the number of elements in the array based on the value of the variable, x.
ReDim dynArray ( x + 1 )
Each time on executing the ReDim statement, the current data stored in the array is lost and the default value is set. But if we want to change the size of the array without losing the previous data, we have to use the Preserve keyword with the ReDim statement. This is shown in the example given below.
ReDim Preserve dynArray ( 50 To 200)
Chapter 7
A control is an object that can be drawn on a Form object to enable or enhance user interaction with an application. Controls have properties that define aspects their appearance, such as position, size and colour, and aspects of their behavior, such as their response to the user input. They can respond to events initiated by the user or set off by the system. For instance, a code could be written in a CommandButton control's click event procedure that would load a file or display a result. In addition to properties and events, methods can also be used to manipulate controls from code. For instance, the move method can be used with some controls to change their location and size. I would like to stress that knowing how and when to set the objects' properties is very important as it can help you to write a good program or you may fail to write a good program. So, I advice you to spend a lot of time playing with the objects' properties Here are some important points about setting up the properties You should set the Caption Property of a control clearly so that a user knows what to do with that command. For example, in the calculator program, all the captions of the command buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons. A lot of programmers like to use a meaningful name for the Name Property may be because it is easier for them to write and read the event procedure and easier to debug or modify the programs later. However, it is not a must to do that as long as you label your objects clearly and use comments in the program whenever you feel necessary One more important property is whether the control is enabled or not Finally, you must also considering making the control visible or invisible at runtime, or when should it become visible or invisible
Chapter 8
* Text can be entered into the text box by assigning the necessary string to the text property of the control * If the user needs to display multiple lines of text in a TextBox, set the MultiLine property to True * To customize the scroll bar combination on a TextBox, set the ScrollBars property. * Scroll bars will always appear on the TextBox when it's MultiLine property is set to True and its ScrollBars property is set to anything except None(0) * If you set the MultilIne property to True, you can set the alignment using the Alignment property. The test is left-justified by default. If the MultiLine property is et to False, then setting the Alignment property has no effect. * In order to work with the part of a text in a text box, the text can be selected using three properties: SelLength - Returns or sets the number of characters selected. SelStart - Returns or sets the starting point of selected text. When no text is selected, SelStart indicates the position of the inserted point. SelText - Returns or sets the string containing the currently selected text. If no text is selected, SelText consists of a zero-length string.
The following Figure summarizes the common TextBox control's properties and methods. Property/ Method Description
Properties Enabled Index Locked MaxLength MousePointer Multiline PasswordChar ScroolBars specifies whether user can interact with this control or not Specifies the control array index If this control is set to True user can use it else if this control is set to false the control cannot be used Specifies the maximum number of characters to be input. Default value is set to 0 that means user can input any number of characters Using this we can set the shape of the mouse pointer when over a TextBox By setting this property to True user can have more than one line in the TextBox This is to specify mask character to be displayed in the TextBox This to set either the vertical scrollbars or horizontal scrollbars to make appear in the TextBox. User can also set it to both vertical and horizontal. This property is used with the Multiline property. Specifies the text to be displayed in the TextBox at runtime This is used to display what text is displayed or in the control By setting this user can make the Textbox control visible or invisible at runtime
Event procedures Change Click GotFocus LostFocus KeyDown KeyUp Action happens when the TextBox changes Action happens when the TextBox is clicked Action happens when the TextBox receives the active focus Action happens when the TextBox loses it focus Called when a key is pressed while the TextBox has the focus Called when a key is released while the TextBox has the focus
Using a Label
Its a graphical control user can use to display uneditable text. Properties of a Label Control * We can write code that changes the caption property displayed by a Label control in response to events at run time. We can also use a label to identify a control, such as TextBox control, That doesn't have its own Caption property. * The Autosize and WordWrap properties should be set if the user wants the Label properly display variable-length lines varying numbers of lines.
Using a CommandButton
We can begin, interrupt or end a process using the CommandButton control Properties of a CommandButton control * To display text on a CommandButton control, set its caption property. * An event can be activated by clicking on the CommandButton. * To set the background colour of the CommandButton, select a colour in the BackColor property. * To set the text colour set the Forecolor property. * Font for the CommandButton control can be selected using the Font property. * To enable or disable the buttons set the Enabled property to True or False * To make visible or invisible the buttons at run time, set the Visible property to True or False. * Tooltips can be added to a button by setting a text to the Tooltip property of the CommandButton. * A button click event is handled whenever a command button is clicked. To add a click event handler, double click the button at design time, which adds a subroutine like the one given below.
You can disable or enable the option button by setting the Enabled property to True os False. You can use the Visible property to make the option button visible to invisible. The following example contains a Label, TextBox, CommandButton and three OptionButton controls. Example Open a new Standard EXE project and the save the Form as Option.frm and save the project as Option.vbp Object Label Name Text TextBox Name Caption CommandButton Name Caption OptionButton Name Caption OptionButton Name Caption Option Button Name Caption Form Name optLuxury Select Room Type frmType optWithMeal Luxury Room optWithoutMeal With Meal cmdExit Without meal txtAmount Exit lblAmount (empty) Property Caption Settings Amount
The application responds to the following events The click event of the optWithoutMeal displays the amount of 2500 in txtAmount. The click event of the optWithMeal displays the amount of 3500 in txtAmount.
The click event of the optLuxuty displays the amount of 5000 in txtAmount. The click event of the cmdExit terminates the program Following code is typed in the click events of the option buttons and the Exit button.
The Application is run by pressing F5 or clicking on the Run icon in the tool bar. By pressing the Exit button the program is terminated.
Chapter 9
user can interact with this control or not Index List ListCount ListIndex Locked MousePointer NewIndex Sorted Style TabStop Text ToolTipIndex Visible Methods AddItem Clear RemoveItem SetFocus Event Procedures Change DropDown GotFocus LostFocus Called when text in ComboBox is changed Called when the ComboBox drop-down list is displayed Called when ComboBox receives the focus Called when ComboBox loses it focus Add an item to the ComboBox Removes all items from the ComboBox Removes the specified item from the ComboBox Transfers focus to the ComboBox Specifies the Control array index String array. Contains the strings displayed in the drop-down list. Starting array index is 0. Integer. Contains the number of drop-down list items Integer. Contains the index of the selected ComboBox item. If an item is not selected, ListIndex is -1 Boolean. Specifies whether user can type or not in the ComboBox Integer. Specifies the shape of the mouse pointer when over the area of the ComboBox Integer. Index of the last item added to the ComboBox. If the ComboBox does not contain any items , NewIndex is -1 Boolean. Specifies whether the ComboBox's items are sorted or not. Integer. Specifies the style of the ComboBox's appearance Boolean. Specifies whether ComboBox receives the focus or not. String. Specifies the selected item in the ComboBox String. Specifies what text is displayed as the ComboBox's tool tip Boolean. Specifies whether ComboBox is visible or not at run time
Run Time : The AddItem method is used to add items to a list at run time. The AddItem method uses the following syntax. Object.AddItemitem, Index
The item argument is a string that represents the text to add to the list The index argument is an integer that indicates where in the list to add the new item. Not giving the index is not a problem, because by default the index is assigned. Following is an example to add item to a combo box. The code is typed in the Form_Load event
Dropdown combo
Simple combo
Dropdown list
The Simple Combo box displays an edit area with an attached list box always visible immediately below the edit area. A simple combo box displays the contents of its list all the time. The user can select an item from the list or type an item in the edit box portion of the combo box. A scroll bar is displayed beside the list if there are too many items to be displayed in the list box area. The Dropdown Combo box first appears as only an edit area with a down arrow button at the right. The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The user can either select a value from the list or type a value in the edit area. The Dropdown list combo box turns the combo box into a Dropdown list box. At run time , the control looks like the Dropdown combo box. The user could click the down arrow to view the list. The difference between Dropdown combo & Dropdown list combo is that the edit area in the Dropdown list combo is disabled. The user can only select an item and cannot type anything in the edit area. Anyway this area displays the selected item. Example This example is to Add , Remove, Clear the list of items and finally close the application. Open a new Standard EXE project is opened an named the Form as Listbox.frm and save the project as Listbox.vbp Design the application as shown below. Object Form Name Text TextBox Name Caption Label Name ListBox Label Name Label Caption Name lblAmount (empty) lblDisplay Name Caption lblName lstName Amount Entered txtName Enter a name frmListBox (empty) Property Caption Settings ListBox
Border Style Caption CommandButton Name Caption CommandButton Name Caption CommandButton Name Caption CommandButton Name
1 Fixed Single Add cmdAdd Remove cmdRemove Clear cmdClear Exit cmdExit
The following event procedures are entered for the TextBox and CommandButton controls.
The click event of the Add button adds the text to the list box that was typed in the Text box. Then the text box is cleared and the focus is got to the text box. The number of entered values will is increased according to the number of items added to the listbox.
Remove button removes the selected item from the list as soon as you pressed the Remove button. The number of items is decreased in the listbox and the value is displayed in the label. The code for the clear button clears the listbox when you press it. And the number of items shown in the label becomes 0.
Chapter 10
The following codes are entered in the vsb1_Change( ) and cmdExit_Click( ) procedures.
Save the project and run the application by pressing F5 or clicking the Run icon in the ToolBar. We can see the value changes as soon as you move the thumb's position of the vertical scroll bar.