Sunteți pe pagina 1din 21

VISUAL BASIC

OBJECTIVE: Understood VB environment with tool bars, controls and


components.

 Programming steps Declaring variables & arrays


 Fundamentals of Graphics & Files data base & SQL

UNIT-1:

 Visual Basic environment:

Visual basic environment is an IDE (integrated development environment) of


Microsoft. Graphical user interface is used with a basic programming language;
it is a first product to provide a graphical programming environment for
developing a user interface.

In this environment, substantial amount of code is replaced by the controls,


where just dragging and dropping is enough to add the control in the interface.
This environment does not have an object oriented programming language
concept.

Attributes and event handling are associated with the controls; default values
are assigned to the controls while it is created and it is possible to change the
default values. This environment primarily allows to create a windows
application, additionally create executable (exe) files, ActiveX controls, and
DLL files. This environment provides a possibility to insert additional logic
based on the appropriate event handlers.

In the Visual Basic Environment preloaded forms are there; usage of these
forms will increase the responsiveness of the application. Usage of constructor
and destructor to set the value to variable will set when the classes get loaded.

In the variable declaration, it is mandatory to use the option explicit and it


forces the declaration of all the variables and avoids careless mistakes.
 Initial VB screen:
 SINGLE DOCUMENT INTERFACE:

Another type of SDI program is common these days. I call it the scatter effect
program. if the user chose the Training module while in the Employee screen,
the program would not replace the Employee screen. It would instead bring up
another form on the desktop, which would look like a separate program
altogether. However, it is not. The different screens can interact with each other
and exchange information.

In this scenario, the user can have four forms open on the desktop, one for each
module (Employee, Training, Payroll, and Scheduling). Can you imagine a
program that could have a dozen or more forms open on the desktop at once?
To me, this is chaos, but I bet you have already used a program that does this.

VB 6.0 has an option to work in an SDI environment or an MDI environment.


The default is MDI, and this keeps things organized. I have a co-worker,
though, who likes the SDI environment. This means that each window is a
separate screen, including all the forms, classes, and modules he has open. I
frequently see him with a few dozen forms scattered all over his desktop.

If you come from the MSVC++ world or you have not programmed yet, you
may not have seen this effect in VB 6.0. However, you do see it in Microsoft
Word. Word used to have an MDI interface. It used to be that you could open
up Word and then open as many documents as you wanted inside Word. Word
is arguably the most ubiquitous program in the world, and I bet many people
like to edit many documents at once. Word is now an SDI application, which
means that each document is in a separate window. In my opinion, all this does
is clutter up the taskbar.

 The Multiform SDI Example

This next example shows you quite a bit about how SDI programs work. It
includes five screens. There is a main screen that lets you choose to edit
different parts of an HR program.

Before you attack the coding of an SDI program, you need to come up with a
plan for how it will work. My plan for this one is based loosely on how
Microsoft Word works:

 The program has a main form with a menu.


 The menu allows the user to choose different parts of the HR program to
work on.
 Each part of the HR program is a new form that appears on the desktop in
a random place.
 The main form has a Window menu option that shows all the HR screens
the user has open.
 The Window option has a submenu item called "Close All Windows" that
closes all the currently open windows.
 The Window menu option of the main screen denotes with a check mark
the child form that is currently in focus.
 If the user chooses one of the forms listed under the Window menu
option, that form gains focus.
 Only one instance of any of the HR forms can be running at a time.
 If the user chooses to edit a form that exists on the desktop, that form will
gain focus.
 If the user closes an existing form, that form is deleted from the Window
menu option.
 If the user closes the main form, the open windows automatically shut
down.

Tool bars and system control and components

Tool bars: A Toolbars in Visual Basic consist of Controls, Containers, Menu


Options, Crystal Report Controls, Data Controls, Dialogs, Components, Printing
controls, that are used in a form to design the interfaces of an application.

 Components of Visual Basic IDE

 The Visual Basic IDE is made up of a number of components.


 Menu Bar:
 Tool Bar:
 CONTROL DESCRIPTION.
 Pointer Provides a way to move and resize the controls form.
 Picture Box Displays icons/bitmaps and meta files. ...
 Text box Used to display message and enter text.
 Frame Serves as a visual and functional container for controls.
 Menu Bar:
 1. This Menu Bar displays the commands that are required to build an
application.
 2. The main menu items have sub menu items that can be chosen when
needed.
 3. The toolbar in the menu bar provide quick access to the commonly
used commands and a button in the toolbar is clicked once to carry out
the action represented by it.
 Tool Bar:
 1. The Toolbox contains a set of controls that are used to place on a
Form at design time thereby creating the user interface area.
 2. Additional controls can be included in the toolbox by using the
Components menu item on the Project menu.

CONTROL DESCRIPTION

 Pointer Provides a way to move and resize the


controls form
 Picture Box Displays icons/bitmaps and meta files. It
displays text or acts as a visual container for other controls.
 Text box Used to display message and enter text.
 Frame Serves as a visual and functional container
for controls
 Command Button Used to carry out the specified action when
the user chooses it.
 Checkbox Displays a True/False or Yes/No option.
 Option Button Option Button control which is a part of an
option group allows the user to select only one option even it displays
multiple choices.
 List Box Displays a list of items from which a user
can select one.
 Combo Box Contains a Text-box and a List Box. This
allows the user to select an item from the drop-down List Box, or to type
in a selection in the Text-box.
 HScrollBar and VScrollBar These controls allow the user to select a
value within the specified range of values
 Timer Executes the timer events at specified
intervals of time
 DriveListBox Displays the valid disk drives and allows
the user to select one of them.
 DirListBox Allows the user to select the directories and
paths, which are displayed.
 FileListBox Displays a set of files from which a user
can select the desired one.
 Shape Used to add shape (rectangle, square or
circle) to a Form
 Line Used to draw straight line to the Form
 Image used to display images such as icons,
bitmaps and meta files. But less capability than the Picture Box
 Data Enables the user to connect to an existing
database and display information from it.
 OLE Used to link or embed an object, display
and manipulate data from other windows based applications.
 Label Displays a text that the user cannot modify
or interact with.

 Project Explorer:-
1. Docked on the right side of the screen, just under the toolbar, is the
Project Explorer window.
2. The Project Explorer as shown in in figure servers as a quick
reference to the various elements of a project namely form, classes and
modules.
3. All of the object that makes up the application is packed in a
project.
4. A simple project will typically contain one form, which is a window
that is designed as part of a program's interface.
5. It is possible to develop any number of forms for use in a program,
although a program may consist of a single form.
6. In addition to forms, the Project Explorer window also lists code
modules and classes.

 Properties Window:-
1. The Properties Window is docked under the Project Explorer
window.
2. The Properties Window exposes the various characteristics of
selected objects.
3. Each and every form in an application is considered an object.
4. Now, each object in Visual Basic has characteristics such as color
and size.
5. Other characteristics not only affect the appearance of the object but
the way it behaves too.
6. All these characteristics of an object are called its properties.
7. Thus, a form has properties and any controls placed on it will have
properties too.
8. All of these properties are displayed in the Properties Window.

 Object Browser:-
1. The Object Browser allows us to browse through the various
properties, events and methods that are made available to us.
2. It is accessed by selecting Object Browser from the View menu or
pressing the key F2.
3. The left column of the Object Browser lists the objects and classes
that are available in the projects that are opened and the controls that have
been referenced in them.
4. It is possible for us to scroll through the list and select the object or
class that we wish to inspect.
5. After an object is picked up from the Classes list, we can see its
members (properties, methods and events) in the right column.
6. A property is represented by a small icon that has a hand holding a
piece of paper.
7. Methods are denoted by little green blocks, while events are
denoted by yellow lightning bolt icon.
 Object naming conversions of controls (prefix)
1. Form -frm
2. Label-lbl
3. TextBox-txt
4. CommandButton-cmd
5. CheckBox -chk
6. OptionButton -opt
7. ComboBox -cbo
8. ListBox-lst
9. Frame-fme
10. PictureBox -pic
11. Image-img
12. Shape-shp
13. Line -lin
14. HScrollBar -hsb
15. VScrollBar -vsb
Key Visual Basic editing features

 Syntax highlighting - includes code folding


 Column/Block mode editing
 Find/Replace and Find/Replace in Files
 Project support
 XML Manager with parsed XML tree view plus ability to move, delete,
and modify nodes and reformat XML
 FTP client with multiple account settings and automatic logon and save
(32-Bit only).
o Includes support for SFTP and FTPS (Control only, Control and
data, Implicit)
o Ability to set a remote (server based) or local (Perl regex based)
filter (provides filtering ability for SFTP)
o Advanced proxy support
o Advanced SSL certificate handling
o Set local default directory for each FTP account

VB File Functions: File Input/Output

The following functions and statements are for file input and output.

Function or Purpose
Statement

Close Closes a file


Eof Checks for end of file
FreeFile Returns the next unused file number
Get Reads bytes from a file
Input Function Returns a string of characters from a file
Input Statement Reads data from a file or from the keyboard
Line Input Reads a line from a sequential file
Loc Returns the current position in an open file
Lock Controls access to some or all of an open file by other
processes
Lof Returns the length of an open file
Open Opens a disk file for I/O
Print Prints data to a file or to the screen
Put Writes data to an open file
Reset Closes all open disk files
Seek Function Returns the current position for a file
Seek Statement Sets the current position for a file
Spc Outputs a given number of spaces
Tab Moves the print position to the given column
Unlock Controls access to some or all of an open file by other
processes
Width Sets the output-line width for an open file
Write Writes data to a sequential file

UNIT-II

The Visual Basic Program Development Process

Visual basic or VB is an “event driven programming language” and “integrated development


environment” of Microsoft. “Graphical user interface” is used with a basic programming
language; it is the first product to provide a graphical programming environment for
developing a user interface.

Steps to create a visual basic project


• Open Microsoft Visual Basic 2010 (Using Microsoft Visual Studio 2010).

• Click File menu, select File → New project

• Select “Windows Forms Application” in the pop-up New Project window and name the
project

• Click File menu → Save All

In the form add the required controls and set the required properties, add the required code to
develop an application, click the run icon or press F5

Code Window

This displays the code associated with the item selected in the Project Explorer window.
Also sometimes referred to as a Module window.
You can even just double click the item in the Project Explorer window.

Displaying the Code Window

To display the code select the item in the Project Explorer window and either choose (View >
Code) or you can alternatively use the shortcut key (F7).
A code module will normally contain more than one procedure or function.
The IDE offers you a choice of whether to display the procedures one at a time (procedure
view) or all at one (full module view).
You can change the views by clicking on the small buttons in the lower-left corner of the
code window. Full Module view is the default.

Use the Code window to write, display, and edit Visual Basic code.
You can open as many Code windows as you have modules, so you can easily view the code
in different forms or modules, and copy and paste between them.
You can open a Code window from:
The Project window, by selecting a form or module, and choosing the View Code button.
A UserForm window, by double-clicking a control or form, choosing Code from the View
menu, or pressing F7.

Code windows can hold four different types of code


1) Subroutines - a set of instructions that performs a particular task
2) Functions - a set of instructions that performs a particular task and then returns a value or
an array.
3) Properties - these are used in class modules
4) Declarations - this is used to declare variables that can be used and referenced from
anywhere in the module (or project).
A single VBA module can store any number of any of the above and how these are organised
is up to you.

Full Module View

icon - Full Module View Icon - Displays the entire code in the module.
This is the default.

horizontal lines separating the procedures and functions.

Procedure View

This can be controlled from (Tools > Options)(Editor Tab, "Default to Full Module View")
icon - Procedure View Icon - Displays the selected procedure. Only one procedure at a time
is displayed in the Code window.
Edit Toolbar

List Properties / Methods - Displays a drop-down list in the code window that
contains all the properties and methods available for the object that precedes the
period (.).
List Constants - Displays a drop-down list in the code window that contains all the
constants that are valid choices for the property that precedes the equal sign (=).
Quick Info - Provides the syntax for a variable, method, function or procedure based
on the location of your position.
Parameter Info - Displays a popup in the code window containing information
about the parameters of the function in which the pointer is located.
Complete Word - Accepts the characters that the editor has automatically appended
as you were typing.
Indent - Shifts all the lines (in the current block) to the next tab stop. No shortcut key
Outdent - Shifts all the lines (in the current block) to the previous tab stop.
Toggle Breakpoint - Toggles the insertion of a breakpoint at the current line.
Comment Block - Adds the comment character ( ' ) to the beginning of each line in
the current selection.
UnComment Block - Removes the comment character ( ' ) from the beginning of
each line in the current selection.
Toggle Bookmark - Toggles the insertioon of a bookmark on or off for the active
line.
Next Bookmark - Moves the focus to the next bookmark in the bookmark stack.
Previous Bookmark - Moves the focus to the previous bookmark in the bookmark
stack.
Clear All Bookmarks - Removes all the breakpoints from the active project (or all
projects ??).

Statements in Visual Basic

A statement in Visual Basic is a complete instruction. It can contain keywords, operators,


variables, constants, and expressions. Each statement belongs to one of the following
categories:

 Declaration Statements, which name a variable, constant, or procedure, and can also
specify a data type.
 Executable Statements, which initiate actions. These statements can call a method or
function, and they can loop or branch through blocks of code. Executable statements
include Assignment Statements, which assign a value or expression to a variable or
constant.

This topic describes each category. Also, this topic describes how to combine multiple
statements on a single line and how to continue a statement over multiple lines.

Declaration statements

You use declaration statements to name and define procedures, variables, properties, arrays,
and constants. When you declare a programming element, you can also define its data type,
access level, and scope. For more information, see Declared Element Characteristics.

The following example contains three declarations.

Public Sub ApplyFormat()


Const limit As Integer = 33
Dim thisWidget As New widget
' Insert code to implement the procedure.
End Sub

The first declaration is the Sub statement. Together with its matching End Sub statement, it
declares a procedure named applyFormat. It also specifies that applyFormat is Public,
which means that any code that can refer to it can call it.

The second declaration is the Const statement, which declares the constant limit, specifying
the Integer data type and a value of 33.

The third declaration is the Dim statement, which declares the variable thisWidget. The data
type is a specific object, namely an object created from the Widget class. You can declare a
variable to be of any elementary data type or of any object type that is exposed in the
application you are using.

Initial Values

When the code containing a declaration statement runs, Visual Basic reserves the memory
required for the declared element. If the element holds a value, Visual Basic initializes it to
the default value for its data type. For more information, see "Behavior" in Dim Statement.

You can assign an initial value to a variable as part of its declaration, as the following
example illustrates.

Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.

If a variable is an object variable, you can explicitly create an instance of its class when you
declare it by using the New Operator keyword, as the following example illustrates.

Dim f As New System.Windows.Forms.Form()


Note that the initial value you specify in a declaration statement is not assigned to a variable
until execution reaches its declaration statement. Until that time, the variable contains the
default value for its data type.

Executable statements

An executable statement performs an action. It can call a procedure, branch to another place
in the code, loop through several statements, or evaluate an expression. An assignment
statement is a special case of an executable statement.

The following example uses an If...Then...Else control structure to run different blocks
of code based on the value of a variable. Within each block of code, a For...Next loop runs
a specified number of times.

Public Sub StartWidget(ByVal aWidget As widget,


ByVal clockwise As Boolean, ByVal revolutions As Integer)
Dim counter As Integer
If clockwise = True Then
For counter = 1 To revolutions
aWidget.SpinClockwise()
Next counter
Else
For counter = 1 To revolutions
aWidget.SpinCounterClockwise()
Next counter
End If
End Sub

The If statement in the preceding example checks the value of the parameter clockwise. If
the value is True, it calls the spinClockwise method of aWidget. If the value is False, it
calls the spinCounterClockwise method of aWidget. The If...Then...Else control
structure ends with End If.

The For...Next loop within each block calls the appropriate method a number of times
equal to the value of the revolutions parameter.

Assignment statements

Assignment statements carry out assignment operations, which consist of taking the value on
the right side of the assignment operator (=) and storing it in the element on the left, as in the
following example.

v = 42

In the preceding example, the assignment statement stores the literal value 42 in the variable
v.

Eligible programming elements

The programming element on the left side of the assignment operator must be able to accept
and store a value. This means it must be a variable or property that is not ReadOnly, or it
must be an array element. In the context of an assignment statement, such an element is
sometimes called an lvalue, for "left value."

The value on the right side of the assignment operator is generated by an expression, which
can consist of any combination of literals, constants, variables, properties, array elements,
other expressions, or function calls. The following example illustrates this.

x = y + z + FindResult(3)

The preceding example adds the value held in variable y to the value held in variable z, and
then adds the value returned by the call to function findResult. The total value of this
expression is then stored in variable x.

Data types in assignment statements

In addition to numeric values, the assignment operator can also assign String values, as the
following example illustrates.

Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.

Compound assignment statements

Compound assignment statements first perform an operation on an expression before


assigning it to a programming element. The following example illustrates one of these
operators, +=, which increments the value of the variable on the left side of the operator by
the value of the expression on the right.

n += 1

The preceding example adds 1 to the value of n, and then stores that new value in n. It is a
shorthand equivalent of the following statement:

n = n + 1

A variety of compound assignment operations can be performed using operators of this type.
For a list of these operators and more information about them, see Assignment Operators.

The concatenation assignment operator (&=) is useful for adding a string to the end of already
existing strings, as the following example illustrates.

Dim q As String = "Sample "


q &= "String"
' q now contains "Sample String".

Type Conversions in Assignment Statements

The value you assign to a variable, property, or array element must be of a data type
appropriate to that destination element. In general, you should try to generate a value of the
same data type as that of the destination element. However, some types can be converted to
other types during assignment.

For information on converting between data types, see Type Conversions in Visual Basic. In
brief, Visual Basic automatically converts a value of a given type to any other type to which
it widens. A widening conversion is one in that always succeeds at run time and does not lose
any data. For example, Visual Basic converts an Integer value to Double when appropriate,
because Integer widens to Double. For more information, see Widening and Narrowing
Conversions.

Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of
data loss. You can perform a narrowing conversion explicitly by using a type conversion
function, or you can direct the compiler to perform all conversions implicitly by setting
Option Strict Off. For more information, see Implicit and Explicit Conversions.

Property Procedures

A property procedure is a series of Visual Basic statements that manipulate a custom property on a
module, class, or structure. Property procedures are also known as property accessors.

Visual Basic provides for the following property procedures:

 A Get procedure returns the value of a property. It is called when you access the
property in an expression.
 A Set procedure sets a property to a value, including an object reference. It is called
when you assign a value to the property.

You usually define property procedures in pairs, using the Get and Set statements, but you
can define either procedure alone if the property is read-only (Get Statement) or write-only
(Set Statement).

You can omit the Get and Set procedure when using an auto-implemented property. For
more information, see Auto-Implemented Properties.

You can define properties in classes, structures, and modules. Properties are Public by
default, which means you can call them from anywhere in your application that can access
the property's container.

For a comparison of properties and variables, see Differences Between Properties and
Variables in Visual Basic.

Declaration Syntax

A property itself is defined by a block of code enclosed within the Property Statement and the
End Property statement. Inside this block, each property procedure appears as an internal
block enclosed within a declaration statement (Get or Set) and the matching End declaration.

The syntax for declaring a property and its procedures is as follows:


[Default] [Modifiers] Property PropertyName[(ParameterList)] [As DataType]
[AccessLevel] Get
' Statements of the Get procedure.
' The following statement returns an expression as the property's
value.
Return Expression
End Get
[AccessLevel] Set[(ByVal NewValue As DataType)]
' Statements of the Set procedure.
' The following statement assigns newvalue as the property's value.
LValue = NewValue
End Set
End Property
- or -
[Default] [Modifiers] Property PropertyName [(ParameterList)] [As DataType]

The Modifiers can specify access level and information regarding overloading, overriding,
sharing, and shadowing, as well as whether the property is read-only or write-only. The
AccessLevel on the Get or Set procedure can be any level that is more restrictive than the
access level specified for the property itself. For more information, see Property Statement.

Data Type

A property's data type and principal access level are defined in the Property statement, not
in the property procedures. A property can have only one data type. For example, you cannot
define a property to store a Decimal value but retrieve a Double value.

Access Level

However, you can define a principal access level for a property and further restrict the access
level in one of its property procedures. For example, you can define a Public property and
then define a Private Set procedure. The Get procedure remains Public. You can change
the access level in only one of a property's procedures, and you can only make it more
restrictive than the principal access level. For more information, see How to: Declare a
Property with Mixed Access Levels.

Parameter Declaration

You declare each parameter the same way you do for Sub Procedures, except that the passing
mechanism must be ByVal.

The syntax for each parameter in the parameter list is as follows:

[Optional] ByVal [ParamArray] parametername As datatype

If the parameter is optional, you must also supply a default value as part of its declaration.
The syntax for specifying a default value is as follows:

Optional ByVal parametername As datatype = defaultvalue


Property Value

In a Get procedure, the return value is supplied to the calling expression as the value of the
property.

In a Set procedure, the new property value is passed to the parameter of the Set statement. If
you explicitly declare a parameter, you must declare it with the same data type as the
property. If you do not declare a parameter, the compiler uses the implicit parameter Value to
represent the new value to be assigned to the property.

Calling Syntax

You invoke a property procedure implicitly by making reference to the property. You use the
name of the property the same way you would use the name of a variable, except that you
must provide values for all arguments that are not optional, and you must enclose the
argument list in parentheses. If no arguments are supplied, you can optionally omit the
parentheses.

The syntax for an implicit call to a Set procedure is as follows:

propertyname[(argumentlist)] = expression

The syntax for an implicit call to a Get procedure is as follows:

lvalue = propertyname[(argumentlist)]

Do While (propertyname[(argumentlist)] > expression)

Illustration of Declaration and Call

The following property stores a full name as two constituent names, the first name and the
last name. When the calling code reads fullName, the Get procedure combines the two
constituent names and returns the full name. When the calling code assigns a new full name,
the Set procedure attempts to break it into two constituent names. If it does not find a space,
it stores it all as the first name.

Dim firstName, lastName As String


Property fullName() As String
Get
If lastName = "" Then
Return firstName
Else
Return firstName & " " & lastName
End If

End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property

Loop Structures (Visual Basic)

Visual Basic loop structures allow you to run one or more lines of code repetitively. You can
repeat the statements in a loop structure until a condition is True, until a condition is False, a
specified number of times, or once for each element in a collection.

The following illustration shows a loop structure that runs a set of statements until a
condition becomes true:

While...End While Statement


While Loops

The While...End While construction runs a set of statements as long as the condition
specified in the While statement is True.

Do Loops

The Do...Loop construction allows you to test a condition at either the beginning or the end of
a loop structure. You can also specify whether to repeat the loop while the condition remains
True or until it becomes True.

For Loops

The For...Next construction performs the loop a set number of times. It uses a loop control
variable, also called a counter, to keep track of the repetitions. You specify the starting and
ending values for this counter, and you can optionally specify the amount by which it
increases from one repetition to the next.
For Each Loops

The For Each...Next construction runs a set of statements once for each element in a
collection. You specify the loop control variable, but you do not have to determine starting or
ending values for it.

S-ar putea să vă placă și