Software Notes by softsys

Search   Chat 


Visual Basic:-

Part - I

Introduction to visual basic
It is an ideal programming language for developing sophisticated professional applications for Microsoft Windows. It makes use of GUI for creating robust and powerful applications. Coding in GUI environment is quite a transition to traditional, linear programming methods where the user is guided through a linear path of execution and is limited to a small set of operations. In a GUI environment, the number of options open to the user is much greater, allowing more freedom to the user and developer. Features such as easier comprehension, user-friendliness, faster application development and many other aspects such as introduction of active X technology and internet feature make visual basic an interesting tool to work with.
Visual basic was developed from the BASIC programming language. Microsoft Corporation created the enhanced version of BASIC called Visual basic for Windows.
Visual basic 6.0 for windows required atleast Microsoft Windows 95 / NT, 486 processor and minimum of 16 MB of ram. A complete installation of the most powerful version of visual basic 6.0 the enterprise edition requires more that 250 MB of hard disk space.

VB comes in 3 editions

  • Learning - Many tools are missing
  • Professional - Learning + Active X controls and documents
  • Enterprise - Most complete edition (Mostly Prefer this)

Types of applications in VB

  • STANDARD EXE :- Typical Application
  • Active X Exe, Active X DLL ( With Professional Edition)
  • Active X Controls :- Develop Your Own Active X Controls
  • Active X Document Exe :- Supports Hyper linking.
  • VB Application Wizard :- steps of setting up the skeleton of new application
  • Addin :- Create Your Own Add-Ins For VB IDE.

3 steps of VB

  • Design
  • Execution
  • Beak
    (VB is point-click operation tool)

Two main themes in developing application in VB
1. Visual Design
2. Event Driven Programming.
Application does not determine the flow, instead the events caused by the user determine the flow of the application.

Event driven programming
Visual basic programs are built around events. Events ere various things that can happen in a program. This will become clearer when studied in contrast to procedural programming. In procedural languages, an application written is executed by checking for the program logically through the program statements, one after another. While in an event driven application, the program statements are executed only when a particular event calls a specific part of the code that is assigned to the event.

VB Project Files
FRM : Individual form file
VBP : Co ordinates overall project. Consists information about available forms, startup form, version and compiler options etc.
VBW : Workspace information - information about the windows which are open in IDE
BAS : Module files

While Programming
1. Be modular
2. Program defensively
3. Don't write ambiguous procedures - dual meaning
4. Avoid deep nesting of conditions or loops
5. Variables should always be defined with the smallest scope possible. Global variables can create complexity.
6. Do not pass global variables to procedures
7. Use & operator to join the strings while + operator for numeric values.

Visual Basic IDE Components - Introduction
Menu Bar Tool bar Project Explorer Properties Window
Form layout Window Toolbox Form Designer Object browser

VB Application Wizard (Steps)
Introduction : Next
Interface type : MDI
Menus : Next
Resources : Next
Internet connectivity - Yes - Next
Standard forms - Splash Screen
Data access forms - Next
Finished - Trial Name - Finish


Data types

Data Type Range
Byte (1 byte) 0 to 255
Integer ( 2 bytes) -32768 to 32767
long ( 4 bytes ) -2,147,483,648 to 2,147,483,647
Single ( 4 bytes ) 10-37 to 1037
double (8 bytes) 10-308 to 10308
currency (8 bytes)  
String Upper limit is 2 billion characters
Date (8 bytes) Date from 1/1/100 to 31/12/9999 with time upto 23:59:59
Boolean ( 2 bytes ) 1 for true, 0 for false
Object (4 bytes)  
Variant  
Usr defined Data type  

Variables
Stores values during a program execution. Must be declared.
Explicit declaration
Variable = placeholder in memory. All values must be explicitly declared. Use dim statement

Variable naming conventions
Must begin with a letter
Can't contain an embedded period or any of the type declaration characters.
Must not exceed 255 characters
Must be unique within its scope.

Variable - Implicit declaration
Need not to declare variables. Vb will create a variable on the spot if it meets an undeclared variable name

Declaration methods
Dim count as integer
Dim area as double, vol as double
Dim area as double, count as integer
Dim a,b,c as integer ( Invalid declaration )

Key words ( Public, Static, Private )
Public :- exists for the lifetime of the application
Private :- Local variables declared as dim or private - live as long as procedure exists.
Static: - variable can preserve its value between procedure calls. (Helps you to minimize the total no of variables.)


Object variable : To access any vb accessible object
Dim a as commandButton
Set a= command1
a.cpation="umesh"

Variant variables
Most flexible data type. Can accommodate all other types in the course of a single program. VB does the conversions for you.
Dim myvar
Dim myvar as variant

There are different ways of declaring variables in Visual Basic.
Explicit declaration / Implicit declaration
Using option explicit statement
Scope of variables

Explicit declaration/ Implicit declaration
Declaring a variable tells visual basic to reserve space in memory. It is not compulsory that a variable should be declared before using it. Automatically whenever visual basic encounters a new variable, it assigns the default variable types and value. This is called as implicit declaration. Though this type of declaration is easier for the user, to have more control over the variables, it is advisable to declare them explicitly. The variables are declared with a Dim statement to name the variable and its type. The AS type clause in the Dim statement allows to define the data type or object type of the variable. This is called as explicit declaration.
For e.g. Dim strname As String

"Option Explicit" Statement
This statement forces the user to declare all the variables. Option explicit statement checks in the module for usage of any undeclared variables and reports an error to the user.

Scope of the variable
A variable is declared in general declaration section of a form, and hence is available to all the procedures. A local variable is variable which is declared inside a procedure. The local variable exists as long as the procedure, in which they are declared, is executing. After that values are lost and memory is freed. Static variables are not reinitialized each time visual basic invokes a procedure and thus retains or preserves value even when a procedure ends.
Static intpermanent As Integer

Variables have lifetime in addition to scope. The values in module level and public variables are preserved for the lifetime of an application.

Module level variables are available to all the procedures in the module. They are declared using the public and private keyword.
Public intpermanent As Integer
Private inttemp As Integer

Declaring a variable with public keyword makes it available throughout the application even for the other modules. At the module level there is no difference between dim and private, but private is preferred because it makes the code easier to read. Public variables should not be declared within a procedure. Public variables in different modules can share the same name and they can be differentiated in code. For example if the public integer variable

Dim  
Private Makes variable available only in the current form / module
Public Makes variable global - available to the rest of the program
ReDim Reallocates storage space for dynamic array variables
Static Variable preserves its value between procedure calls
Type Declares user type

Constants ( Do not change values )
Public constant gvf as single = 9.81
const pi as double = 3.1415926
const pi2 as double = 2 * pi
Place all constant values in one module.
Example
Const pi As Double = 3.1415926

Private Sub cmd_radius_Click()
r = InputBox("Enter redius")
MsgBox "The area of circle is " & pi * r * r
End Sub


Immediate window
When you issue VB command here; they execute immediately. Use for designing and debugging. Use this window for execution of statements, examine values of controls on form, and set the values of controls on form.


Immediate Solutions - Environment Setup - Tools - Options
Introduction to Quick Info, Auto List Members, Data Tips, Syntax checking - VB Code Colors

Aligning, Sizing and Spacing Controls - Format Menu

Using Visual basic predefined forms menus and projects - Add form - Vb Folder - Templates - Existing (Visual Component Manager)

Setting VB Project's Version Information - Project Properties

Code Window : Procedure view, Full Module view


Tab Order
Using tabindex property
Tabindex of is control =0 then 1 and so on. When a given control's tabindex is changed VB automatically renumbers the tab order of the remaining controls.

When you don't want user to move to a control, you can remove it from the tab order = set tabstop property to false.


Property
It is a named attribute of a programming object. Properties define the characteristic of an object such as size color etc. or sometimes the way in which it behaves.
Common properties
Name appearance backcolor forecolor font caption text width height left top enabled visible.
The properties that are discussed above are design-time properties that can be set at the design time by sleeting the property window. But certain properties cannot be set at design time for example Current X, Current Y properties of form.

Methods
Are the actions that the objects carry out. Predefined procedures.
Common methods (clear, additem, removeitem). Methods are carried out without any program assistance. Hides the implementation details of the control features. A method accepts one or more parameters that tell it exactly how to perform an action

Events
Determine controls reaction to external conditions. The subroutine that determines how a control reacts to and event is called an event handler.

Use of Msgbox() and Inputbox() - Print Method

Condition Checking

'1. If --- then ----- else (optional)-----endif
'2. Select case ----- end select

Simple if
'if <condition> then
'statement/s
'endif

if with else
'if <condition> then
'statement/s
'else
'statement/s
'endif

Nested if
'if <condition> then
'statement/s
'if <condition> then
'statement/s
'else
'statement/s
'endif
'endif

Select --- Case --- End Select
Select Case <Variable name>
Case <Comparison String>
Action
Case <Comparison String>
Action
End Select

With --- End With Statement

LOOPS
1. Do while (Condition true)

2. Do Until (Condition false)
Do
[Statements]
[Exit do]
[Statements]
Loop [{while | until } condition]

3. While …. Wend

4. For …. Next

5. For Each Loop
Dim IDarray(1 To 3)
IDarray(1) = 1
IDarray(2) = 2
IDarray(3) = 3

For Each ArrayItem In IDarray
MsgBox (Str(ArrayItem))
Next ArraryItem

'Accept 5 numbers from users and display Max and Min
a = InputBox("Enter any Number")
max = Val(a)
min = Val(a)
For i = 2 To 5
a = InputBox("Enter any Number")
If Val(a) > max Then
max = Val(a)
Else
If Val(a) < min Then
min = Val(a)
End If
End If

Next i
Print min
Print max

'Fibonacci Series
a = 0
b = 1
Print a
Print b
c = a + b
While c <= 55
Print c
a = b
b = c
c = a + b
Wend


Dim a, f As Long

Private Sub Command1_Click()
'Factorial
f = 1
a = InputBox("Enter any number")
For i = Val(a) To 1 Step -1
f = f * i
Next i
Print f
End Sub

Bookmarks - Edit - Toggle Bookmark

Introduction to Common Properties
Form, Label, Text, Combo, List, Timer, Shape, Scroll bar

VB Controls
Controls have properties that define aspects of their appearance, such as position, size, and color, and aspects of their behavior, such as their response to user input.
Visual basic controls are categorized into standards controls, ActiveX controls and insertable objects.
Standard controls such as label text frame controls are contained inside i.e. VB EXE
Active X controls exist as separate files with OCX extension.
Insertable objects are custom controls that can be added to the Toolbox. For example Word document, PowerPoint presentation etc.


Introduction to Common Controls
1. Label
2. Text Box
3. Command Button
4. Frame
5. Shape
6. Picture Box and Image Box
7. Combo Box / List Box
These control present lists of choices from which the user can select one or more.
List :- user cannot enter data into a list, can only select items.

Combo :- contains multiple items, occupies less space on screen, expandable list box control, user can enter items in the combo-box control.

Important properties :- multi-select, sorted, style, datasource, datafield, additem, removeitem, clear

List :- ( listcount, list() array that holds the list's items, listindex, selected, selcount, newindex ( returns the index of the most recently added item to the list box.)
** assignment :- transfer items between lists

Use of Various Events

1. Click
2. Double Click
3. Form Load
4. Mouse Move
5. Timer
6. Change event :- Takes place every time the user changes the indicators position and releases the mouse button.

Scroll Event :- It occurs continuously while the indicator is moving. When the mouse is released, then a single change event is triggered.

Slider similar to scrollBars ( new property is SelStart :- to start the initial position value of the slider.
Saving Images ( keep autoredraw property = true to save image successfully. Saves only BMP files.
SavePicture Picture1.Picture , "c:\abc.bmp"

DragDrop
Property :- DragMode
Events :- DragDrop , DragOver
Nearly every control has a dragmode property which determines whether a control can be dragged or not. Settings 0 for manual, 1 for automatic

DragDrop event of receiver control
Text3.Text = Source.Text
Picture1.Picture = Source.Picture
** Assignment :- drag an item of list box on another list box.

Graphics
Form1.Line draws lines and ractangles
Form1,Circle draws circle, ellipse, arc.

Form1.Line(x1,y1) - (x2,y2),color,BF,
Width of line - DrawWidth property

When circle executes the current X and current Y co-ordinates are set to the center point.

Drawing Methods
Print Line Circle Point(returns color value of point) Pset(set the color of the point) PaintPicture

Scroll bar Control

Drive Box Directory box and List Box

Check Box & Option Control
A CheckBox control displays an X when selected; the X disappears when the CheckBox is cleared. Use this control to give the user a True/False or Yes/No option. You can use CheckBox controls in groups to display multiple choices from which the user can select one or more.

Text1.FontBold = Not Text1.FontBold
Text1.FontUnderline = Not Text1.FontUnderline
Text1.FontStrikethru = Not Text1.FontStrikethru
Text1.FontItalic = Not Text1.FontItalic

'Oct()
Returns a Variant (String) representing the octal value of a number.
Syntax
Oct(number)
Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is Oct returns
Null Null
Empty Zero (0)
Any other number Up to 11 octal characters

Command Button
Style :- Graphic
Backcolour
Forecolour
Downpicture
Disabled picture

Dragover property


Programming Conventions (VB Black Book Page 28 to 33)

Operators and operator precedence

Arithmetic Comparison Logical
Exponentiation ^ Equality = Not
Negation - Inequality <> And
Multiplication & Division Less than < Or
Modulus mod Greater than > Xor
Addition & Subtraction Less than or equal to <= Eqv
String concatenation Greater than or equal to >= imp
String concatenation Like Is

Functions

String Handling Functions
StrComp(), Lcase(), Ucase(), Len(), Format(), Instr(), Left(), Ltrim(), Right(), Rtrim(), Trim(), Asc(), Chr()

Important Date functions
Date, Now, Time
Dateadd()
Date diff()

Datepart()
This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.

Dim TheDate As Date ' Declare variables.
TheDate = InputBox("Enter a date:")
msgbox DatePart("q", TheDate)

yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second


Datevalue()

This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant or Date variable, for example, MyDate = #2/12/69#.

Dim MyDate
MyDate = DateValue("February 12, 1969") ' Return a date.

Timevalue()
This example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant or Date variable, for example, MyTime = #4:35:17 PM#.

Dim MyTime
MyTime = TimeValue("4:35:17 PM") ' Return a time.

Dateserial()
This example uses the DateSerial function to return the date for the specified year, month, and day.

Dim MyDate
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12) ' Return a date.

Day()
Month()
Year()
Weekday()


Data Verification Functions
IsArray( ), IsEmpty(), IsError(), IsDate(), IsMissing(), IsNull(), IsNumeric(), IsObject()

Empty value
Any variable declared but not assigned any values i.e. its value is empty
IsEmpty()
Var = Empty

Null value
Only if variable is assinged as null i.e var = null

IsNull()
To check for the type of a variable use function VarType(). It will return a number to show type of variable.

Data Conversion functions

Cbool() Cbyte() CCur() CVar()
CSng() Cint() CDate() CVerr()
CStr() CLng() CDbl()  

OCT()
Hex()
Format (currentval)

Math Functions
Abs(), Atn() - Arc Tangent, Cos(), Exp(), Fix(), Int(), Log(), Rnd(), Sin(), Sqr(), Tan()

User defined data types (Similar to Structures in C )
Type Checkrecord
Checkno as integer
Checkdate as date
Checkamt as single
Checkpaidto as string *50
EndType

Dim check1 as checkrecord
Dim checks(100) as checkrecord


MDI Form
A mulitple document interface form is a window that acts as a background of an applicaion and is a container for forms that have their MDI child property set to true.
One application can have only one MDI for object. MDI can only have Menus and PictureBox controls.

Use of OLE Objects

Menu Builder

Popmenu
Create menu - file -> other options
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbRightButton Then
Form1.PopupMenu file
End If
End Sub

1 = VbRight Button
2 = VbLeftButton
4 = VbmiddleButton


User Defined Functions & Procedures


Changing the mouse Pointer
Command1.MousePointer = vbHourglass
Command1.MousePointer = vbCross

vbArrow , vbCrosshair, vbIbeam, vbIconPointer, vbSizePointer, vbSizeNS, vbArrowQuestion, vbNoDrop, vbUpArrow


Error handling in VB

  • On error resume next
  • On error GoTo = Writing your own error handler

Dim a As Integer
Private Sub cmd_start_Click()

On Error GoTo Ehandler

a = InputBox("Enter your age", "Errorhandler")

If a <= 18 Then
MsgBox "Minor"
Else
MsgBox "Major"
End If

Ehandler:
If Err() = 13 Then
MsgBox "Data type mismatch"
End If

If Err() Then
MsgBox Err.Description
End If
End Sub

Modal form
Form2.Show 1 : Do not allow cascading effect
Form2.Show : Allows cascading effect


Pset Method
Private Sub cmd_start_Click()
Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
Form1.PSet (9000 * Rnd, 9000 * Rnd)
'To find color of pixel at location 400,700
pixelcolor = Point(400, 700)
End Sub

Visual basic - Arrays
A sequence of variables by the same name can be referred using arrays. The individual elements of an array are identified using an index. Arrays have upper and lower bounds and the elements have to lie within those bounds. Each index number in an array is allocated individual memory space and hence users must evade declaring arrays of larger size than required. One can declare any array of any of the basic data types including variant, user defined types and objet variables. The individual elements of any array are all of the same data type.
There are two types of arrays in visual basic.

Fixed size arrays :- Can be declared by giving a name to the array with the upper limit in the parentheses. The upper limit should always be within the range of Long data type.
Dim Arr(9) As Integer
0 to 9 i.e. 10 elements. "Arr" is the name of the array

If one want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the "To" keyword.
Dim Arr(1 To 10) As Integer
In the above case array of 10 elements is declared but with indexes running from 1 to 10.

Multidimensional array
It is used when we need to represent or store related information of different dimensions. When we want to mention X & Y co-ordinates.
Dim Marks(50,50) 50 by 50 array

It is possible to define explicit lower limits for one or both the dimensions as for fixed sized arrays
Dim studMarks (101 To 200, 1 To 100)

Dynamic array
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.
Dim Newarray()
The actual number of elements can be allocated using a ReDim statement.
ReDim Newarray(y+1)
It allocates the number of elements in the array based on the value of the variable Y.
Every time on executing the Redim statement, the current data stored in the array is lost and the default value is set. To preserve the data we have to use the Preserve keyword.
ReDim Preserve Newarray(ubound(firstarray)+1)

Turning bounds checking On or Off
Project Properties - Compile Tab - Advanced Optimization
Privave Sub Command_Click()
Dim Address (1 to 10) as integer
Address(1)=1 No Error
Address(11)=11 Error
End Sub



Calculator Code

Connection Code