Introduction to Visual Programming - NPR Arts and Science College
Introduction to Visual Programming - NPR Arts and Science College
UNIT-I:
Introduction-starting & exiting visual basic-using project explorer- working
with forms- using toolbox- working with projects- printing projects- building &
running applications.
Adding code &using events- using code window- using naming conventions-
using variable- scope- subroutines & functions.
UNIT-II:
Using intrinsic visual basic controls- label & textbox controls- using command
button control- using frame, checkbox, option button controls- list box and combo box
controls- formatting controls- using control arrays- using tab order.
Working with strings - using strings, converting string, concatenating strings,
formatting strings, manipulating strings, comparing strings.
UNIT-III:
Working with numbers - using numeric values- using numeric operators- math
functions- random numbers.
Using control statement- IF &IIF- select case- do-for- exit statements.
UNIT-IV:
Using dialogue boxes- Msg box- input box- common dialogue control- open &
save as dialogue box- font dialogue box- print dialogue box- show help method.
Using menus- creating menus- assign code to menu- creating shortcut menu –
using picture box- rich text box.
UNIT-V:
Using files & databases- opening, closing & deleting files, and reading writing
to files.
UNIT-I
INTRODUCTION TO V.B:
The “visual” part refers to the method used to create the graphical user
interface (GUI). Rather than writing numerous lines code to describe the appearance
and location and location of interface elements, you simply add prebuilt objects into
place on screen. If you‟ve ever used a drawing program such as paint, you al ready
have most of the skills necessary to create an effective user interface.
The original Visual Basic for DOS and Visual Basic for Windows
were introduced in 1991.
Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993.
Visual Basic 4.0 released in late 1995 (added 32 bit application support).
Visual Basic 5.0 released in late 1996. New environment, supported creation of
ActiveX controls, deleted 16 bit application support.
Visual Basic 6.0 - released in mid 1998s - some identified new features of Visual
Basic 6.0:
Faster compiler
ActiveX document.
DHTML Application that helps to test browser
applications.
IIS application that helps to build server based
applications.
Web browser control.
FTP/HTTO supports through a custom control.
Winsock control.
Has an excellent integrated help facility and books
online
Includes good debugging facilities.
Has many wizards that help automate repetitive tasks
Use many database access methods to get different
types of data
a. New
b. Existing
c. Recent
Existing -> used to open the project which was already created.
Standard EXE
Active EXE
ActiveX DLL(dynamic link library)
ActiveX Control
VB application wizard
VB Wizard manager
ActiveX document DLL
Data project
Add in
ActiveX Document EXE
Menu bar
The menu bar contains the command required to build a visual basic
application. It lies across the top of the screen .Menu bar have submenu item. Menu
bar contains 13 submenu items they are as
Tool bar
The tool bar contains shortcut of some popular menu items. It provides
quick access to commonly use command.
Project explore window
The project explorer server as a quick reference to the form, classes
and modules in current project. It
is arranged in a tree order . It has three tabs
a. view code
b. view object
c. toggle folder
Properties window
It has two sides, left side showing the name of the property where as
right side showing the value of that property. This window can be viewed as
alphabetical
or categorized manner
Tool box
Tools or object are called as controls. There are 21 standard controls
other controls can be add through
Project -> components -> controls
Form designer
It enables to add controls, graphics, pictures to a form to define the
interface in the desired look .we can see only one form or code window at a time.
Code window
It is used to write the code we want to attach to an object. Two
dropdown list boxes on the top. Left is for object where as right for events.
Immediate window
It is used to debug the errors during runtime. It is also known as debug
window
Object browser
It allows us to browse the various properties, events and methods. We
can access it by pressing F2 (or)
View->object browser
The project explorer displays a hierarchical list of the projects and all
the items contained in a project. The elements of your project explorer window are as
follows:
View code displays the code window where code is written and edited
View object displays the object window for the selected item. An existing
form, module. ActiveX object
Toggle folders that hides and show the object folders while still showing
the individual items contained with them.
Shortcut key : CTRL + R
Visual basic allows the project explorer window to be moved so that it can be
placed where it works best for you. The following are the methods that can be used to
move the project explorer window.
Click the title bar and drag the window to a new location.
Double click the title bar to move the window to its last undocked location.
The window can still be docked to any side of it‟s parent window, which is the
visual basic window.
Right-click on the window and choose dockable from the shortcut menu to
move the window to its last undocked location. This makes the window no
longer dockable.
Double click the title bar a second time returns the project explorer to its
previous docked location.
Move the mouse pointer over one of the borders until it takes the shape of the
double headed arrow. Then click and drag the border to the size that you desire. Don‟t
forget that an undock able project explorer window can be minimized and maximized.
Maximizing the window allows you to quickly view the largest possible number of
objects.
Now you know how to navigate the project explorer. You also know how to
move it around, change its size, and even Alter its behavior. Now, it‟s time to learn
how to use it.
Using the project explorer to view objects:
The form layout window allows you to visually position your forms at
design time. All forms that are visible in the environment are displayed. W hen you
place your cursor over a form. If you press the mouse button you can position the
form where you want it to appear at runtime
Altering a form
The size and position of the form can be changed during design time
and runtime during
Design time the size of the form can be changed by the following ways
1. By clicking the maximize, minimize, close controls on the form
or by double clicking the title bar of the form.
2. By using the sizing handler and with the help of mouse, the size
of form can be changed
3. By using shortcut keys shift + arrow keys
4. By using width and height properties of the properties window
Working with form layout window:
During runtime, the size and position of the form can be changed by the following
ways
1. Move the cursor to the form layout window(the cursor will change to a
four-headed arrow)
2. Drag the form to the position in which we want it to appear when the
user starts our program.
3. To change the size of the form during runtime, window state property
is used.
It contains three options
Normal -> The form is displayed as the user designed during design
time.
Maximize -> The form is maximized during runtime
Minimize -> The form is minimized during runtime
The size of form is changed during runtime using maximize, minimize and close
control
The visual basic tool box contains the tools you use to draw controls on your
forms. The tools are for working with the form is found on the menus.
The toolbox itself contains the icons representing the controls we can add to
our forms. The Tools are object are called as controls. Among these there are 21
standard controls we can add any if required through
Pointer control
The first item on the toolbox is not a control but is used to manipulate controls
after we create them click the pointer when we want to select, resize, or move existing
controls
Label control
Label box display only read only text.
The caption of the label box can be changed during runtime through
code.
It is always used to give message to the user.
It is used to provide information.
Label box control looks like .
Timer control
It can execute code and regular intervals .fixed size control.
It is invisible at run time.
Ole control
Ole stands for object linking embedded.
It is used to connect other application.
This control in a window you can place your form to host
document from application such as MS word, MS excel.
Creating controls
To get a control on a form by double clicking on its icon in the toolbox. The
control appears in the middle of the form with its default size and shape.
Example
To draw an item from the toolbox on a form at a specific location with a
specified size
1. Move the mouse pointer to the tool we want to use and click
2. Move the mouse pointer to the form. The mouse pointer has changed
from an arrow to a shape like a crosshair
3. Hold the mouse button down and drag the mouse to create the object.
Then the control appears on the form.
Sizing handles
When we release the mouse button, the control has eight little boxes
Visual basic comes with many controls that are not automatically
included in the toolbox. Follow these steps to add controls to the toolbox:
Locking controls
By choosing format->lock controls or lock controls tool from the tool bar use
can lock the control in the form (i.e) we can‟t move if we lock. Choosing, it again
presses up the controls so that we can move them again.
Deleting controls
To delete a controls
Move the mouse pointer until it is inside the control, and click
the left mouse button to select it.
Press delete or open the edit menu and choose the delete option
by pressing Alt + E, D.
Project window:
The project explorer displays a hierarchical list of the projects and all
the items contained in a project. The elements of your project explorer window are as
follows:
View code displays the code window where code is written and edited
View object displays the object window for the selected item. An existing
form, module. ActiveX object
Toggle folders that hide and show the object folders while still showing
the individual items contained with them.
Shortcut key : CTRL + R
All visual basic applications are based upon a project. A project file
(VBP) doesn‟t contain many forms, controls, or code. It contains the list of all objects
and files that are used in the projects.
Creating projects:
New projects can be created when you first start visual basic. You can
also create projects after starting visual basic. To create a new project, follow these
steps:
The default project is created with a single form. Most projects require the use
of more than one form and sometimes the use of other types of objects. To add an
object to a project, choose the type of object you want from the project menu. The
choices are as follows:
form
MDI form
Module
Class module
User control
Property page
User document
ActiveX designer
file
Printing projects:
Save form
Save form item I used to save the form that is currently working on.
Shortcut keys to save the forms are Ctrl + S or Alt + F, S. The default extension for
form files is form. Visual basic save form dialog box as shown below
The file name is changed and click the save button, the file name will
be saved with the user defined file name.
Save form as
Save form as is used to rename the file name of form. The default
extension of form is frm. The copy of form is also stored in another place with the file
name unless the save form as option. Shortcut key is Ctrl + A
(Or) Alt + F, A
Save project
Save project is used to save the entire project. To select this option,
press Alt + F, V or use the save project tool. Visual basic opens a dialog box as shown
above
The default extension is .vbp.
When we save a project using save project option, visual basic does not
keep a backup copy of the previous version. To save a backup copy of a project does
the following
1. Save each of the files on the project with a new name
2. Choose the save project as option and give the project file
(.vbp) a new name.
Save project as
Save project as is used to rename the project name. The copy of project
is also stored in some other location with their project name under save project as
option
Running an application:
You can run your applications using any of the following methods:
press f5
click the run button on the toolbar
choose start from the run menu
EVENTS:
Example: click event for a command button gets triggered when you click on the
button.
Load:
Syntax:
Private sub form _load() or
Private sub mdiform _load()
Unload:
Occurs when a form is about to be removed from the screen. When that
form is reloaded, the contents of all its controls are reinitialized. This
event is triggered by a user closing the form using close command on
the control menu or an unload statement.
Syntax:
Private sub form _ unload (cancel as integer)
Query unload:
Syntax:
Private sub form _ query unload (cancel as integer, unload mode as integer)
Private sub MDI Form _ query unload (cancel as integer, unload mode as
integer)
When windows informs visual basic that an event has taken place for
one of it‟s object, visual basic automatically calls the event procedure that has the
name corresponding to the event.
The event‟s name established an association between the object and the
code.
An event procedure for a control combines the control‟s actual name
(specified in the name property), an underscore (_), and the event name. For instance,
if you want a command button name cmd command1 to invoke an event procedure
when it is clicked, you would use the procedure command1_click ()
For controls:
Visual basic automatically creates procedures for forms and controls. You can
view and edit the code for an event procedure in the code editor window.
Note: when writing procedures for new controls, it‟s good idea to set the name
property immediately after creating the control. Because code procedures are attached
to the controls, changing the name of the control after a procedure is written breaks
the association between the code and the control.
`
The code window is used to write, display, and edit visual basic
code. The different code window elements are as follows:
Declaring variables:
The manner by which variables are declared and where they are
declared and where they are declared determines how they can be used by your
application.
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double Cdbl
Integer Cint
Long CLng
Single CSng
String Cstr
Variant Cvar
Error CVErr
To use conversion function, you place it on right hand side of a calculation statement
as follows:
For example:
A counter that stores the number of items a procedure or code block executes.
To save a value returned forms a method or function.
To store directory names and filenames.
Visual basic can store strings of text, numbers, object or even data
where the types is unknown. Visual basic provides the following data types.
String(variable length)
String(fixed length)
Length
Long integer
Single
Double
Currency
Date
Boolean
Variant
Object
String
The string data type holds character. It takes 2bytes per character to store
string variable can hold about 2billion characters. The identifier for this variable is $
Example; String variable$
Integer
Integer variable hold small integer values (between-32768 and -32,767). Its
storage size is 2 bytes. Variable will only, be capable of holding integers is to use the
percent sign (%)At the end of the variable name
Example; integer variable%=3
Byte`
Its storage size is 1byte. The range between (0 to 255). It can hold integers.
Long integer
It storage size is 4bytes and the range (between -2,147,483,648 to
2,147,483,647) the identifier for this variables is the ampersand (&)
Example; long integer variable&=123456789
Single precision
The least accurate is called single precision. They have a decimal point, but
we can be sure of the accuracy of only seven digits. It storage size is 4bytes. The
identifier for this variable is the(!)
Example; single precision variable! = 12.345
Double precision
The double precision data type is used when we need numbers with up to 16
places of accuracy calculation are also approximate for these variables. Double
precision variable are mainly used in scientific calculation in VB. The identifier used
is pound sign (#), storage size is 8bytes
Example; double precision variable# =12.345#
Currency
The storage size is 8bytes. The identifier for this variable is @. Its range from
-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Example; currency variable@ = 12.345@
Date
The date data type is used to store both date and time information. Its storage
size is 8bytes. Its range is january1,100 to december31,9999 AM/PM for time or a 24-
hour clock.
Example; date1 = #january1,2000 11:59 PM#
Date1 =# january1,2000 23:59#
Boolean
The data to be either true or false. The storage size, is 2byte.
Variant
A variant can be any of the preceding data types plus null and empty.
Note: visual basic doesn‟t require that you explicitly select a variable type when you
declared variables. By default visual basic assigns variables the variant data type. It
can store any type of data. But this reduces the speed and requires a large amount of
data when compared to other data types.
Declaring variables:
The manner by which variables are declared and where they are
declared and where they are declared determines how they can be used by your
application.
Syntax
Static varname [as type]
Static variable are useful for maintaining counters that are used only
within a procedure.
Example Following procedure declares the variable icount by using the static
keyword. Each time the procedure runs, 1 is added to the value stored in icount.
Static icount as integer
Icount = icount +1
Msgbox”The count is now”& icount
Constant
VB prevents the value of a constant from being changed during
program execution. (i.e) value that never change during execution of a program. To
create a constant, we use the const statement with the following syntax
[Public /private] const constname [as type] = expression
Example
Public const PI as double = 3.1415
For example:
Sub cmdcommand1_click ()
Getdata
End sub
FUNCTIONS
Introduction to string:
Lblmessage.caption=”answer is incorrect”
Function Action
Strcomp compare two strings.
Lcase, Ucase convert to lowercase or
uppercase.
Space, string create string of repeating
character.
Len find length of a string
Lset, Rset justify a string
Instr, left, ltrim, mid, right, trim manipulate strings
Strconv convert strings
Asc, chr returns numeric or character
values
UNIT-II
Standard controls:
There are 21 standard controls in VB6.0 which are seen in the standard
toolbox. This section deals with the descriptions, properties and methods of these
controls.
Label control:
A label control displays text that the user cannot edit. You can use labels to
identify controls, such as text boxes and scroll bars that do not have their own caption
property. Labels can be transparent, so that the text appears to be placed directly on
the form.
Property value
Name ibititle
Caption controls tutor
Next, you should open the font property page and make the font as large as possible,
with bold styling. After doing this, you may have to resize the label so that all of the
text is visible. There are two ways to resize a control
Select the control and drag one of its sides with a sizing handle.
Change the width or height property of the control.
The Auto size property causes controls to automatically increase their size so that
anything being displayed within them is fully visible.
Select the label in the middle of the form and change the following properties
Property value
Name ibi About
Auto size true
caption written by scott L warner for teach yourself visual basic.
Change the following properties for the lable at the bottom of the form:
Property value
Alignment 2-center
Appearance 0-flat
Back color button face
Name ibi close
caption ok
in addition to changing the preceding properties, increase the font size to 14.
Now, all of the properties are set the labels of the about box, which should look
similar to the below figure
Textbox control:
Text boxes are versatile controls that can be used to get input from the user or
to displayed text. The icon in the toolbox for a text box show the letters ab, . It is
used to display an it allows to accept text from the user.
Properties
Gives the textbox its own identity alwsys starts with text.
Text
To text that appears on the text box whether user given data or result.
Alignment
This property controls how text is displayed
0-left alignment (default)
1-right alignment
2-center alignment
Multiline
Properties
The properties of the command button are as follow
The caption
This property determines what the user sees on the face of the button. To
change the caption of the command button, move to the properties by using the mouse
or the UPARROW and DOWNARROW key (shift + ctrl + c).
Visible
It determines whether the command button is visible or not it can only be set
to true or false.
Enabled
It sets to true/false set this property to false to make the command button
unusable. ([i.e] it will not respond to any event concerning that button)
Font
It controls which font is used for the caption of the button. The font
characteristics – bold, italic, font name an so on.
Height, width
These properties define the height and width of the command button. The
height of the button. The width property changes the width of the button.
Left, top
It determiner the distance between the command button and the left edge and
top of the form.
Mouse pointer
By setting this property the mouse pointer is something different than the
usual arrow.
Access keys
VB makes it easy to set upon access key. For any object that has a caption, all
we have to do is place an ampersand (&) in front of the letter we want to be the access
key.
Properties
Name-> gives the control its own identity always start with label.
Auto size-> by setting this property to true, the width and height of the label is
changed automatically according to the text typed.
Word wrap-> set this property to true to enable word wrapping. This is automatically
set when we create a control array.
Example
If we copy a label box and then use VB prompt ask us whether to create a
control array or not, if yes then control array is created
Borer style
Font
Fore color
Back color ->use to give the control background color for this back style should be
selected us back style – 2 option
0-transparend- This does not set the selected .back color for the control.
Message boxes
Message box s displayed which displayed a message to the user and waits for
the user to respond t is a model box
Syntax
Msgbox message inbox, type of box, title of box.
Example
Msgbox ”welcome”
Message box can hold maximum of 1024 characters.
The following table shows the constant value and their meaning
Message icon.
The grid
It is important for accurately positioning controls. In order to control the grid,
choose tools->options (ALT + T ,O) and then go to the general page on the options
dialog box there are 4propertes.
Show grid
Turn the grid on or off by changing the show grid setting the default setting is
on.
Checkbox control:
A checkbox indicates whether a particular
Condition is on or off. You use check boxes in an
Application to give users true/false or yes/no options.
Because check boxes work independently of each other,
a user can select any number of check boxes at the
same.
Dropdown combo
Simple combo
Dropdown list box
Properties
Name – gives the controls its own identity always starts with combo
Sel length – return the number of the selected text.
Sel start – returns the starting position of the selected text
Sel text – returns the selected text in some of their controls.
Style – it has 3 options
1. 0-droupdown – it looks like a textbox and no arrow is at
the end.
2. 1-simple combo - The user can select this choice using
up arrow or down arrow.
3. 2-droup down – it looks like a list box. In this we can
select the item from the existing list and user cannot
give his own choice as input
Properties
1. Name – it gives the control its own identity. Always starts with list.
2. Sel count – displays the number of selected items in the list box.
3. Style – it has 2 options
0-standared – it is default style in which a check box
is not included before an item
1-chicked – it displays or include a checkbox before the
item. It is possible only when the multiselect property is
set as none
You can add and remove controls in a control array at run time using the load
and unload statements. However, the control to be added must be an element of an
existing control array. You must have created a control at design time with the index
property set to „0‟. Then, at run time, use this syntax to load and unload the controls.
Where:
Object is the name of the control to add to or delete from the control
array.
Index is the control‟s index value in the array.
When using windows applications, you can use the tab key to move the focus
to one control to another. This is a feature that many users have come to depend upon.
Well-planned forms can be worked with using only the keyboard. By using the tab
key to move from one control to the next. For example, when filling out a from that
asks for a name and birthday, such as, you can use the tab key to move the focus from
one control to another. The focus should original be on the text box for the first name,
then middle initial ,last name, and birthday.
Introduction to string:
Lblmessage.caption=”answer is incorrect”
Function Action
Strcomp compare two strings.
Lcase, Ucase convert to lowercase or
uppercase.
Space, string create string of repeating
character.
Len find length of a string
Lset, Rset justify a string
Instr, left, ltrim, mid, right, trim manipulate strings
Strconv convert strings
Asc, chr returns numeric or character
value
Len;
The Len function counts the characters in a string
and returns the length as an integer.
Syntax:
Example:
Result:5
Instr
Syntax:
Where:
1. Start position is a numeric expression that sets the start position for the
start position for the search of substring in string. If start position is
omitted, instr begins searching at the first position.
2. String is the string being searched.
3. Substring is the string you are looking for in string.
Left
The left function returns characters from the left
hand side.
Syntax:
Where:
Right
The right function returns characters from right
hand side of string.
Syntax:
Where:
Mid
The mid function returns characters from any part
of a string.
Syntax:
Where:
Ltrim
The ltrim function strips leading spaces from a
String.
Syntax:
Ltrim (string)
Where:
1. String is the string that should be stripped off the leading spaces.
Rtrim
The trim function strips triling spaces from a
string.
Syntax:
Rtrim (string)
Where:
2. String is the string that should be stripped off the trailing spaces.
Example:
Debug.print rtrim (“hello world”)&”!”
Debug.print”hello world “&”!”
Result:
Hello world!
Hello world !
Trim
The trim functions strips leading and triling spaces from a string.
Syntax:
Trim (String)
Example:
Debug.print trim (“ hello world “)& Len (trim(“hello world”))
Result:
Hello world11
Hello world 22
Strcomp
In case-sensitive comparisons, capital letters have a
Different value than lowercase letters. Remember that the ASCII value of a lowercase
letter is greater than the capital letter by32;asc (“a”)=65and that the ASC(“a”)=97.
in case-sensitive comparisons, “A”=”a” returns false.
Syntax:
Strcomp (string1,string2[,compare])
Where:
1) String1 and string2 are any valid string comparision-0 for case sensitive
comparisions.
The following code returns the value when two strings are compared in the
binary(case sensitive) or textual(non case-sensitive) format.
FORMATTING STRING:
The format function is used to format dates, numbers and string with
ease. You can choose from format‟s predefined named formats, such as currency or
fixed, or insist on finer control by creating your own user-defined format.
The format function returns a string, which you can use for either screen or
pointer output.
Syntax:
Format (expression [,format[,first day of week[,firstweekofyear]]])
Example:
Result:
1234
$1,234.00
1234.00
1,234.00
1.23%
1.2se-02
no
true
on
Manipulating strings:
String can be manipulated in many ways. Parts of the string can be trimmed
off to eliminate unwanted characters. Functions can extract portions of a string or add
a series of characters to a string. The following sections address each of these
possibilities.
Comparing string:
There are occasions, when these named formats will not be enough and
you will require more control over your number formats. In these situation, you may
use a combination of a series of special formatting characters to control exactly how
the formats your numbers.
Example:
Dim mysingle as single
Dim myinteger as integer
Dim mycurrency as currency
Mysingle=0.23
Myinteger=123
Mycurrency=12234324.9
Debug.print format(myinteger, “00000”)
Debug.print format(myinteger, “#####”)
Debug.print format(mysingle, “###%”)
Debug.print format(mycurrency, “###,###,##0.00”)
Debug.print format(0,”###,###,##0.00”)
Debug.print format(mycurrency, “\$###,###,##0.00”)
Result:
00123
123
23%
12,234,324.90
0.00
$12,234,324.90
More on strings
Strings are variables and constant that hold alphanumeric values. To
concatenate two strings, use the ampersand (&)
Example
Title$ = “queen”
Name$ = “Elizabeth”
Numerals$ = “I”
First Elizabeth = title$&name$&numeral$
Current queen = title$&name$&numerals$&numerals$.
Output
Queen Elizabeth I
Queen Elizabeth II
ANSI/ASCII codes
Example
Print chr (2270->prints the letter pi(п)
Example
Print chr(34);
Print “Welcome”
Print chr(34);
Output
“Welcome”
The value 34 display quotation marks.
Example
Dim shortstring as string * string*10
Dim strshort as string *10
More on numbers
When we write the code to assign a value to a numeric variable in VB, w can‟t
use comma to delineate thousand, VB will not let we enter code like;
Dim I as integer
I = 1,234
Declaring variables:
Before going going into the details of declaring variables for storing numeric
values, let‟s review the different numeric data types. The following are the numeric
data types in visual basic:
Byte
Integer
Long
Single
Double
Currency
Intexample=1
Intexample=returntwo
Intexample=”3”
Numbering system:
There are three different numbering systems that are commonly used in visual
basic:
Decimal
Hexadecimal
Octal
The values of numeric variables are often manipulated to derive new values.
These variables are manipulated using operators, such as + and- this allows
applications to dynamically determine numeric values. For example, the amount
someone should be paid for a week‟s work can be determined by multiplying(*) the
number of hours worked by the amount paid for each hour of work. Further
operations could be performed to determined the amount of taxes to be taken out of a
paycheck..
Numeric operator
The five fundamentals arithmetic operations
Operator operations
+ Addition
- Subtraction (denotes
Negative number)
/ division
* Multiplication
^ Exponentiation
\ Integer division
(Back slash)
Arithmetic operators:
The following sections discuss the arithmetic operators available in visual
basic. Trigonometric functions are discussed later in this chapter in the section “using
trigonometric functions”.
Math functions:
The math functions are visual basic help perform common mathematical tasks
to determine values that night otherwise be difficult to determine. As you build
applications. For example, if you don‟t create applications that perform complex
drawing and graphing you may never use the trigonometric functions.
The abs function returns the absolute value of a number. An absolute value is
not positive or negative. It is the value of a number without regard to being negative
in value. For example, both of the following statements set in example equal to 10:
Intexample=abs(10)
Intexample=abs(-10)
Syntax:
Exp(number)
And also the fix and int functions are essentially the same:
Syntax:
Fix(number)
Int(number)
The rnd function generates a random number that is less than 1 and greater
than 0. it returns the value as a single data type, using the following syntax:
Rnd[(number)]
Randomize [number]
UNIT-III
Control structures:
o If…….then statements
o If……..then……elseif statements
o Select case statements
The relational operators and the logical operators are used in the condition
portion of the if…..then block.
If more than one of the conditions in a conditional structure is true, only the
code statements enclosed by the first true condition are executed.
If……then statements:
Single-line:
Example:
If condition then
Statements
End if
If......then….else statements:
If condition then
[statements]
else
[statement]
end if
Example:
If……then…elseif statements
syntax:
If condition1 then
[statements]
elseif condition2 then
[statements]
else
[statements]
else if
This example shows the syntax for the select case structure:
end select
select case structure is deal for testing the value of an expression against
ranges possible values. This example shows how to use the select case structure to
evaluate a number against four different ranges and determine a bonus based on an
individual range of values.
Looping structures:
Looping structures allow you to specify the conditions under which you would
like your program to execute a set of instructions repetitively. To determine which
looping structure to use, consider two questions:
Do….loop
For….next
Do…..loop structures:
Do…..loop structures give your program the ability to execute a block of code
an indeterminate number of times. While there are several variations of the do loops,
they fall into two major categories: loops where an expression is evaluated at the end
of the loop, and loops where the expression is evaluated at the beginning.
The loop structures that evaluate the expression at the end are:
Do….loop while. Repeats the code block until the test expression evaluates as
false.
Do….loop until. Repeats the code block until the test expression evaluates as
false.
Do….loop while
Do……loop while structures check the condition after executing the code and
repeat a code block untile the test expression evaluates as false. Do……loop while
structures use the following syntax:
Do
[statement]
loop while[condition]
for example, this code will loop untilled the correct password is entered:
do
passwd =inputtext(“enter your password”)
loop while passwd<>”Rajesh”
Do……loop until
Do…….loop until structures check the condition the code and repeat a code
block until the test expression evaluates as true. Do…..loop until structures use the
following syntax:
Do
[statements]
loop until[condition]
for example, this code do loop until the no button is clicked in a message box.
Do
Loop count=loopcount+1
Loop until Msgbox(“loop….?,vb yes no)=vbno
Do while……loop
Do while condition
[statements]
loop
This example test for the end file condition and reads lines until the end of the file is
reached:
Do while endoflife=true
[read and process next line in file]
[set endoffile to true if end of file is encountered]
loop
Do until….loop
Do until….loop structures check the condition before executing the code. The
code in the loop is executed only if the condition evaluates as false, and repeats until
the test expression evaluates as true.
Syntax:
Do until condition
[Statements]
Loop
Example:
Do until endoffile=true
[read and process next line in file]
[set endoffile to true if end of file is encountered]
loop
For…..next statement
When you know how many times a code block will execute, it is easier to write and
maintained. The for…..next statement executes a code block a specific number of
times.
Syntax:
Example:
Sglaverage=sqltotalscore/instnumstud
Exiting a loop
The exit statement allows you to exit directly from a for…..loop, do loop, sub
procedure, or function procedure. Syntax:
Do until[condition]
[statements]
if[condition]then
exit do
end if
loop
UNIT-IV
Dialog boxes:
Types:
Dialog boxes are either modal or modeless. A model dialog box must be
closed(hidden or unloaded) before you can continue working with the rest of the
application. For example, a dialog box is modal if it requires you to click ok or cancel
before you can switch to another form or dialog box.
Example:
Form1.show vbmodal
Modules dialog boxes let you shift the focus between the dialog box and another form
without having to close the dialog box. You can continue to work elsewhere in the
current application while the dialog box is displayed.modless dialog boxes are rare.
From the edit menu. The find dialog box in visual basic is an example of a modules
dialog box.
Predefined dialog boxes can be added to the application easily by using the
inputbox function and the Msgbox function. The predefined dialog boxes are always
modal.
The inputbox()displays a prompt in a dialog box, waits for the user to input
text or click a button, and returns a string containing the contents of the text box.
Syntax:
Inputbox(prompt[,title][,default][,xpos][,ypos])
The Msgbox() displays a message in a dialog box, waits for the user to click a
button, and returns an-integer indicating which button the user clicked.
Syntax:
Msgbox(prompt[,buttons][,title]
The Msgbox function displays the dialog box that is created using the
arguments supplied to the function. This is a simple dialog box that displays a
message and accepts feedback from user only through the form ofd closing the dialog
box-no text can be entered by the users.
Many times this function is used to supply information to users without
expecting any feedback for example the following dialog box is used to notify the
user that it has completed its search and the item was found.
The user has no choice but to press the ok button to close this dialog box.
Displaying information is the most basic task for the Msgbox function.
The prompt is the only argument that is required for the Msgbox function.
Syntax:
The prompt and title arguments have the same effect on dialog box created
with inputbox as they did using Msgbox- as do the help file and context arguments. In
addition, only the prompt argument is required.
The inputbox returns a string value. If the user click oj\k button or presses the
enter key, the string contained in the text box is returned. But if the user clicks the
cancel button or presses the esc key, an empty string is returned, regardless of what
the text box contains.
The windows operating system contains a set of dialog boxes that are used to
complete frequently used tasks, such as the following:
Open a file
Save a file
Select a color
Select a font
Print or change print options
Show help
These dialog boxes are defined in COMDLG32,OCX, which must be present
in the windows system directory. Visual basic‟s common dialog control contains and
provides access to the dialog boxes defined in this file.
The common dialog box control is a non-visual object, meaning that it is
never visible at run time. Because of this, it can be placed any where on a form
without regard to the way it looks or how it interacts with users; it si never seen and
has no direct interaction with users.
Any application that deals with opening and saving files needs a mechanism
for doing so. The common dialog control offers a solution for both: the open and save
as dialog box. These dialog boxes are discussed together because they are so similar.
The only different between them is the default dialog title and the caption on the
action button.
The following dialog box ix opened using the shown open method of the
common dialog control.
Setting the properties of the open and save as dialog boxes:
The open and save as dialog boxes are affected by the same properties of the
common dialog control. At design time, these properties are set either in the
properties window or in the property page of the common dialog box, which is shown
in below.
Using the color dialog control box:
Application dealing with formatted text or graphics normally give users the
ability to change colors. A text editor might allow the color of the text to be changed
to emphasize a word or phrase, and varying colors are nearly a requirement for
graphical presentations. Although very specialized programs might required very
specialized input to make these types of adjustments in color, most applications
benefit from using the common dialog control color dialog box.
The font dialog box allows to make choices about how text is displayed. This
dialog box offers choices based upon the fonts that are installed on the user‟s
machine. These fonts are divided into two categories: screen fonts and printer fonts.
Screen fonts determine how text is displayed on your monitor, and printer fonts
control the appearance of printed text.
The flags property of the common dialog control must be set to a value
specifying the fonts to be used before the shown font method is called to display the
font dialog box.
Example program
Menu:
A menu in visual basic terms is a type of control. Menus like controls have
properties and events but do not have any methods. Also each menu8 item is a
separate menu control. You can set some of the properties of a menu when you add
the menu item using menu editor.
A menu control displays a custom menu for your application. A menu can include
commands, submenus and separate bars. Each menu you create can have up to four
levels of submenus.
Creating menus:
Menus are created using the menu editor, which is a dialog box. Submenus
and separator bars are also created with the menu editor. Most properties of menus
can be set in the properties window.
To open the menu editor, open a form in the form window. Then ,choose
menu editor from the tools menu or press ctrl+e shows the menu editor with no
entries.
Adding menu commands:
The first level of a menu provides only the titles to be displayed in the menu
bar. At this stage, nothing would happen if you ran the application and clicked on one
of the menus. Menu items must be added to the next level of the menu structure.
These items appear as commands in the menu of the title in the level immediately
above them.
i. Open the form from the previous section in the form window.
ii. Open the menu editor.
iii. Select the edit menu from the list box at the bottom of the dialog box.
Adding submenus:
Visual basic allows you to create up to five levels of submenus for each menu
title.
I. Open the form from the previous section in the form window.
II. Open the menu editor.
III. Select the save menu from the list box at the bottom of the
dialog box.
IV. Click the insert button.
The menu editor creates a menu structure; menu titles, menu commands,
submenu, separator bars, access keys, and shortcut keys. These menu items work
together to present users with a series of these menu items work together to present
users with a series of commands in a logical manner. However, the menu editor only
creates the structure of the menu. The commands that the menu items.
like . The main difference between picture boxes and forms is that we use the
height and width properties of the picture box rather than the scale height and
scale width properties of the form. There are two ways to display an image inside
a picture box at design time. The first is to load a picture by setting the picture
property via the properties window. Another is to paste a picture directly into the
picture box choose edit/paste (ALT + E, P (or) CTRL + V).
To add a picture while a VB project is running. Suppose we
have two picture boxes, picture1, picture2, and picture1 has an image and pictue2
does not have image. Then a line of code like
Picture2.picture = picture1.picture.
Copies the image from the first picture box to the second picture box.
Syntax
Picture box name. Picture = load picture ([file name])
Or, for forms
[Form name].picture = load picture ([file name])
Properties
Auto size - If true, automatically resizes the controls to display its entire
contents otherwise false.
Events
The events are click, double click event or key events.
Methods
Cls- clear graphical and text generation at run time from a picture box.
Syntax
Object.cls
Coding window
Output
Textbox:
Text boxes are versatile controls that can be used to get input from the user or
to display text.
It allows the user to enter and edit text while also providing more advanced
formatting features than the conventional text box control. The icon looks like
Toolbox controls is a custom controls, we will add it to the toolbox if it is not
already there to do this
choose project-> components ->components dialog box opens.
Choose Microsoft rich text box control 6.0
The properties of rich text box are as follows.
Sel text – returns or sets a string equal to the currently selected text.
Sel bold – change the currently selected text to bold.
Example
rich text box1.sel bold = true
Sel strike thru – change the currently selected text to strike thru.
Sel font size – it lets us to change the size of the currently selected text.
Syntax
Object Sel font size = size
Maximum value of Sel font size is 2,160 points
UNIT-V
Files:
A file consists of a series of related bytes located on a disk. When your
application accesses a file, it must assume what the bytes are supposed to represent (
characters, data records, integers, string, and so on).
Depending upon what kind of data the file contains, you use the appropriate file
access type. In visual basic.
There are three types of file access:
Sequential
Random
Binary
Functions and statements used with all three types of file access:
Dir()
Syntax:
Dir[(pathname[,attributes])]
Filelen()
Syntax:
Filelen(pathname)
Lof()
Syntax:
Lof(filenumber)
Eof()
Syntax:
Eof(filename)
Freefile()
Syntax:
Freefile[(Rangenumber)]
Fso
Fso is a part of Microsoft scripting runtime. which is referred to as scripting.
Fso is a class with in the scripting application
Syntax
Set fso = create object(“scripting .fso”)
To create an object that provides access to the computer file system.
Example
Dim fso as object
Set fso = create object(“scripting .fso”)
Output
Set fso = nothing
Opening files
Fso is used to create a text file. It is method used to open a text file.
Example
Dim fso as object
Set fso = create object(“scripting.fso”)
Set ts = fso.open text file (“c:\a.text,8,true,-2).
Step 1: you can create fso object.
Step2: open text file methods create a text scream object and assigning to
variable.
Step3:the text is read form file ad return to the file using the text scream object.
step4: c:\a.text = it is a file name.
-2 it is open to a file using default
-1 it is open to a file using default Unicode.
Syntax
Set ts c=fso. Open text file, filename, iomode, create, format)
Database:
Database terms:
There are many types of data base terms in visual basic (i.e),
Sql
Table
Primary key
Foreign key
Indexes
Queries
Record set
File menu
Utility menu
Window menu
Forms and dialog boxes
Visdata as a sample
Visual basic provides several methods for working with files. This book
demonstrates the manipulation of text files using the file system object. The fso object
is an activeX object and provide all of the versatility and ease-of-use that you find in
most activeX object.
Opening file:
Before you can work with any text file, you need a reference to the file.
Obtaining this reference is commonly known as opening the file. The fso object uses
the opentextfile method to do this, as in the following:
Closing file:
after opening a file, you most likely perform several actions on the file. For
example, you might write several new lines of text to the file. When finished with the
file, you should close the file, which is done using the close method of the text stream
object.
Deleting files:
Certain files have a limited time span in which they are useful. For whatever
reason a file is no longer needed, the file is usually deleted to free up storage space.
Fso.deletefile filespec [,force]
After you are familiar with creating the fso object and using its open text file
method to return a text stream object, you can begin to manipulate the files that the
text stream object is associate with the following sections.
Text could be retrieved from a file for a number of reasoned. The methods
used to retrieve the text can be just as varied. This section discusses the different
methods used to retrieve text from a file.
Reading characters:
Syntax:
Text stream7.read(characters)
Reading lines:
Syntax:
Textstream.readline
Writing to files:
Writing text to a file is a little simpler than reading it. Either you want to add
characters to the current line of text or you want to create a new line of text, in some
case, you might want to do both.