Unit 1,2&3
Unit 1,2&3
Unit 1,2&3
Net Programming
In a perfect world, you wouldn't need .NET Framework. The makers of all your crucial
applications would have the time and resources to fully patch together their applications
into self-contained packages, because developing for Windows would be an intuitive,
mostly high-level process that independent developers could nail down in fairly quick
order. So nobody besides developers would need a package like .NET, which provides
applications with an orderly way to access databases, web services, and other
communication tools.
One problem .NET installations often run into is a need for space, even if your system
might not make that explicit. The 4.0 version of .NET for standard 32-bit Windows
systems requires 850 MB of free space on your primary Windows drive; a 64-bit
Windows system needs 2 GB free, and Windows usually won't ask you if you have space
on another partition to spare. If your free space is smaller than these amounts, you'll need
to look at your hard drive and free up some space.
Another common problem involves older versions of .NET and, perhaps, their
misbehavior on your system. Head into your Add/Remove Programs section in Control
Panel (or "Uninstall Programs" in newer Windows setups) and search for any
installations related to ".NET Framework," or something very similar. Try removing
them from here, through the standard uninstall procedure, and then try installing your
newer .NET framework again. If that still fails, it's time to turn to the .NET Framework
Cleanup Tool, which was made by Microsoft itself to tidy up and set things straight
following tricky .NET installations.
Layered application designs are extremely popular because they increase application
performance, scalability, flexibility and code reuse. In the classic three tier design,
applications break down into three major areas of functionality:
The data layer manages the physical storage and retrieval of data
The business layer maintains business rules and logic
The presentation layer houses the user interface and related presentation code.
Inside each of these tiers there may also exist a series of sub-layers that provide an even
more granular break up the functional areas of the application. Figure outlines a basic
three tired architecture in ASP.NET along with some of the sub-tiers that you may
encounter:
This Layer only communicates with Business Access Layer. Data Access Layer contains the method
that helps Business Access Layer. Business layer class's methods call the Data Access Layer Class
methods to perform some required action with database such as insertion, deletion, updation etc.
All database related connection codes are written in this layer only such as sql query, stored
procedure etc.
During this time, Microsoft was improving its technology, and they introduced
COM+, Microsoft Transaction Server (MTS), and Distributed Network Architecture
(DNA).These technologies allowed more sophisticated interactions among components,
such as object pooling, events, and transactions.
associated with Microsoft, its flexibility and scalability means that theoretically it could
be usable on other platforms in the future.
IL is a stack-based assembly language that gets converted to byte code during execution
of a virtual machine. It is defined by the common language infrastructure (CLI)
specification. As IL is used for automatic generation of compiled code, there is no need
to learn its syntax. This term is also known as Microsoft intermediate language (MSIL)
or common intermediate language (CIL).
Visual Basic .NET, part of the Visual Studio .NET suite, boasts a number of new
features designed to make programming faster and easier. In addition to the basic
features, such as variables, data types, constants, arrays, enumerations, operators,
expressions, statements, and procedures.
Some of the new features of Visual Basic are:
1. Assemblies: An EXE or a DLL file that forms the basis of deployment, version
control, reuse, and security permissions of an application.
2. Namespaces: The components of assemblies, namespaces primarily organize the
objects present in the assemblies. An assembly can contain more than one
namespace.
3. Adding references: You need to add a reference to the external object that you
want to use in your current application.
4. Attributes: The tags that are used to provide additional information about the
elements defined in a Visual Basic .NET program. Some of the most common uses
of attributes are
To explain COM properties for classes, interfaces, and methods
To explain assemblies
IDE has more features such as through this we can store the code online, format the
code and optimize the code and it has a lot of plug-in and extensions which is very
helpful in creating a rich application.
The IDE's toolbar looks like a word processor. This is called IDE because we can
access the necessary tools to develop the software application.
IDE components
The components of the IDE are as follows: -
Menu System: After you've started Visual Basic and have seen the Start page, you
often turn to the menu system to proceed, as when you want to create a new project and
use the File|New|Project menu item to bring up the New Project dialog box. The IDE
menu system is very involved, with many items to choose from-and you don't even see it
all at once. The menu system changes as you make selections in the rest of the IDE.
Menu bar: The menu bar is also common for all document windows. It contents
command required and build an application. The main menu items have some menu
items that can be chosen when needed.
Tool bar: The tool bars gives us quick access to commonly used menu command.
Beside the main tool bar, which is displays by default window the menu bar, visual basic
IDE provides additional tool bar for specific purpose. The four built in tool bar are
standard, edit, debug and from editor. By default, standard tool bar appear immediately
below the menu bar.
Form designer: For a software application, form objects are like building blocks. This is
the window from which the user interacts at the beginning of the application. Forms have
their own properties, events, and methods that we can control. The form window is a
window where we draw our application.
Tool box: The tool box contains the icon of the control we can place on a form to create
the application’s user interface. By default tool box contains a pointer icon and twenty
other icons of ActiveX controls. The tool boxes appear at the left side on screen by
default. User can change its position anywhere on the form. Even tool box can be turn
off on screen. To place a control on a form, we first select it with a mouse and then move
the mouse over the form. When the mouse is over the form, the curser turns into a large
plus sign, and we can draw control on the form, just as we would draw a circle using a
drawing application. The size of the circle determines the size of the control.
Property window: Every object has properties associated with it. The properties
window is docked under the project explorer window. The properties window allows us
to assign or change properties associated with a particular object. Properties are
SHASHI RAJ, BMSCW /Page 9
VB.Net Programming
attributes such as size, position etc. like a form, each control has its own set of
properties. Some properties like width, height are common to both form and controls,
while other properties are unique to form or control. Control offend differ in the number
and type of properties.
Code window: Normally code window not appear on screen because it is automatically
hidden. When we double click any control in the form, a code window will open. Visual
basic code window consist of two list boxes. Both list boxes appear at the top of the code
window. The left most list box is called object list box and right most list box is called
procedure list box.
Object list box allows us to select event procedure associated with a particular object.
The procedure list box allows us to select the event procedure associated with a
particular type of event such as click, drag drop, key down, mouse down etc.
Object Explorer: This tool lets you look at all the members of an object at once, The
Object Explorer helps open up any mysterious objects that Visual Basic has added to
your code so you can see what's going on inside. To open the Object Explorer, select
View|Other Windows|Object Explorer. The Object Explorer shows all the objects in your
program and gives you access to what's going on in all of them. To close the Object
Explorer, just click the X button at its upper
Solution Explorer: The Solution Explorer tracks the items in your projects; to add new
items, you can use the menu items in the Project menu, such as Add Windows Form and
Add User Control. To add new empty modules and classes to a project, you can use the
Project|Add New Items menu item. The Solution Explorer sees things in terms of files.
There, the References folder holds the currently referenced items (such as namespaces)
in a project, Assembly Info.vb is the file that holds information about the assembly
you're creating, and Form1.vb is the file that holds the code for the form under design.
Class View Window: If you click the Class View tab under the Solution Explorer,
you'll see the Class View window, this view presents solutions and projects in terms of
the classes they contain, and the members of these classes. Using the Class View
window gives you an easy way of jumping to a member of class that you want to access
quickly-just find it in the Class View window, and double-click it to bring it up in a code
designer.
Server Explorer: it's a great tool to help make distant servers feel less distant, because
you can see everything you need in an easy graphical environment. You can drag and
drop whole items onto Windows forms or Web forms from the Server Explorer.
Task List :It is another useful window. To see it, select the View|Show Tasks|All .As its
name implies, the Task List displays tasks that VB .NET assumes you still have to take
care of, and when you click a task, the corresponding location in a code designer
appears.
Output Window: Gives you the results of building and running programs.
Visual Basic Form is the container for all the controls that make up the user interface.
Every window you see in a running visual basic application is a form, thus the terms
form and window describe the same entity. Visual Studio creates a default form for you
when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be
buttons to close, maximize and minimize the form. If you click the icon on the top left
corner, it opens the control menu, which contains the various commands to control the
form like to move control from one place to another place, to maximize or minimize the
form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These
properties can be set or read during application execution. You can refer to Microsoft
documentation for a complete list of properties associated with a Form control:
Form Methods
The following are some of the commonly used methods of the Form class. You can refer
to Microsoft documentation for a complete list of methods associated with forms control:
Form Events
Following table lists down various important events related to a form. You can refer to
Microsoft documentation for a complete list of events associated with forms control:
Controls
An object is a type of user interface element you create on a Visual Basic form by using
a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic
control consists of three important elements:
Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.
Object.Property= Value
Where
Form1.Caption ="Hello"
You can set any of the form properties using Properties Window. Most of the properties
can be set or read during application execution. You can refer to Microsoft
documentation for a complete list of properties associated with different controls and
restrictions applied to them.
Control Methods
A method is a procedure created as a member of a class and they cause an object to do
something. Methods are used to access or manipulate the characteristics of an object or a
variable. There are mainly two categories of methods you will use in your classes:
If you are using a control such as one of those provided by the Toolbox, you can call any
of its public methods. The requirements of such a method depend on the class being
used.
If none of the existing methods can perform your desired task, you can add a method to a
class.
For example, the MessageBox control has a method named Show, which is called in the
code snippet below:
PublicClass Form1
PrivateSub Button1_Click(ByVal sender AsSystem.Object,ByVal e AsSystem.EventArgs)
Handles Button1.Click
MessageBox.Show ("Hello, World")
EndSub
EndClass
Control Events
An event is a signal that informs an application that something important has occurred.
For example, when a user clicks a control on a form, the form can raise a Click event
and call a procedure that handles the event. There are various types of events associated
with a Form like click, double click, close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You can see
this code by double clicking the code which will give you a complete list of the all
events associated with Form control:
Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The
control classes are defined in the System.Windows.Forms namespace.
The following table lists some of the commonly used controls:
Data Types
Data types refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
Variables
What is a Variable?
A variable is a simple name used to store the value of a specific data type in
computer memory.
In VB.NET , each variable has a particular data type that determines the size,
range, and fixed space in computer memory.
With the help of variable, we can perform several operations and manipulate
data values in any programming language.
The declaration of a variable is simple that requires a variable name and data
type followed by a Dim.
A Dim is used in Class, Module, structure, Sub, procedure.
Syntax:
Name Descriptions
Dim It is used to declare and allocate the space for one or more
variables in memory.
Variable_Name It defines the name of the variable to store the values.
As It is a keyword that allows you to define the data type in the
declaration statement.
Data Type It defines a data type that allows variables to store data types such
as Char, String, Integer, Decimal, Long, etc.
Value Assign a value to the variable.
There are some valid declarations of variables along with their data type definition,
as shown below:
Further, if we want to declare more than one variable in the same line, we must
separate each variable with a comma.
Syntax:
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3
As DataType3
For example
Dim x As Integer
x = 25
MsgBox("The value of variable x is : " & x)
Constants
The name constant refers to a fixed value that cannot be changed during the
execution of a program. It is also known as literals.
These constants can be of any data type, such as Integer, Double, String,
Decimal, Single, character, enum, etc.
Declaration of Constants
Further, if we want to declare more than one variable in the same line, we must
separate each variable with a comma, as shown below.
Const1.vb
Calculations
• Calculations can be performed with variables, constants, properties of certain
objects, and numeric literals.
• Do not use strings in calculations
• Values from Text property of Text Boxes
– Are strings, even if they contain numeric data
– Must be converted to a numeric data type before performing a calculation
Operators
Operator is a special symbol that tells the compiler to perform the specific logical or
mathematical operation on the data values. The data value itself (which can be either a
variable or a constant) is called an operand, and the Operator performs
various operations on the operand.
3+2-1
The symbol + and - are the Operators, and the 3, 2, and 1 are operands.
o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
Arithmetic Operators
Comparison Operators
As the name suggests, the Comparison Operator is used to compare the value of two
variables or operands for the various condition such as greater, less than or equal, etc.
and returns a Boolean value either true or false based on the condition.
<> It is a Non-Equality Operator that checks whether the (A <> B), check Non-
value of the two operands is not equal; it returns true; Equality
otherwise, it shows false.
> A greater than symbol or Operator is used to (A > B); if yes, TRUE,
determine whether the value of the left operand is
greater than the value of the right operand; If the Else FALSE
condition is true, it returns TRUE; otherwise, it
shows FALSE value.
< It is a less than symbol which checks whether the (A < B); if the
value of the left operand is less than the value of the condition is true,
right operand; If the condition is true, it returns returns TRUE else
TRUE; otherwise, it shows FALSE value. FALSE
>= It is greater than equal to which checks two A >= B
conditions whether the first operand is greater than or
equal to the second operand; if yes, it returns TRUE;
otherwise, it shows False.
<= This symbol represents less than equal to which A <= B
determines the first operand is less than or equal to
the second operand, and if the condition is true, it
returns TRUE; otherwise, it shows FALSE.
Is The Is Operator is used to validate whether the two result = obj1 Is obj2
objects reference the same variable or object; If the
test is true, it returns True; otherwise, the result is
False. In short, it checks the equality of the objects.
An Is Operator is also used to determine whether the
object refers to a valid object.
IsNot The IsNot Operator is similar to Is Operator, except Result = obj1 IsNot
that the two object references the different object; if obj2
yes, the result is True; otherwise, the result is False.
Like The Like Operator is used to check the pattern result = string Like the
expression of string variable; And if the pattern pattern, the pattern
matched, the result is True; otherwise, it returns represents the series of
False. characters used by Like
Operator.
The logical and bitwise Operators work with Boolean (true or false) conditions, and if
the conditions become true, it returns a Boolean value. The following are the logical and
bitwise Operators used to perform the various logical operations such as And, Or, Not,
etc. on the operands (variables). Suppose there are two operand A and B, where A is
True, and B is False.
Not(A And B)
is True
Xor It is an Exclusive OR Operator that represents, whether both A Xor B is
the expression is true or false, the result is True; otherwise, True
the result is False.
AndAlso It is a logical AND Operator that performs short-circuit A AndAlso B
operation on the variables, and if both the operands are true, = False
the result is True else the result is False.
OrElse It is a logical OR Operator that perform short-circuit A OrElse B =
operation on Boolean data. If anyone of the operand is true, True
the result is True else the result is False.
IsFalse The IsFalse Operator is used to determine whether an
expression is False.
IsTrue The IsTrue Operator is used to determine whether an
expression is True.
The Bit Shit Operators are used to perform the bit shift operations on binary values either
to the right or to the left.
Operator Description
AND The Binary AND Operator are used to copy the common binary bit in the
result if the bit exists in both operands.
OR The Binary OR Operator is used to copy a common binary bit in the result if
Assignment Operators
The Assignment Operators are used to assign the value to variables in VB.NET.
Concatenation Operators
Sequential Construct
The sequential construct means the statements are being executed sequentially. This
represents the default flow of statements.
Selection Construct
The selection construct means the execution of statement(s) depending upon the
condition-test. If a condition evaluates to true, a course-of-action (a set of statements) is
followed otherwise another course-of-action is followed. This construct is also called
decision construct as it helps in decision making.
Iterative Constructs
The iterative or repetitive constructs means repetition of a set-of-statements depending
upon a condition-test. A set-of-statements are repeated again and again till the condition
or Boolean Expression evaluates to true. The iteration constructs are also called as
looping constructs.
Selection Constructs
1) If statement
2) Select Case statement
The If Statement: If statements of VB come in various forms & are given below:
1) If..Then Statement
2) If..Then..Else Statement
3) If..Then..ElseIf Statement
4) Nested Ifs
1. If..Then Statement
An If..Then statement tests a particular condition; if the condition evaluates to true, a
course-of-action is followed otherwise it is ignored.
Syntax:
If (Boolean expression) Then
Statements
End If
2. If..Then..Else Statement
If..Then..Else statement provides an alternate choice to the user i.e. if the condition is
true then a set of statements are executed otherwise another set of statements are
executed.
Syntax:
Else
VB Statement(s)
End If
3. If..Then..ElseIf Statement
If..Then..ElseIf statement is used to test a number of mutually exclusive cases and only
executes one set of statements for the case that is true first.
Syntax:
4. Nested Ifs
A nested If is an if that has another If in its if’s body or in its else’s body.
Syntax:
If (expresssion 1) Then
If (expression 2 ) Then
Statement 1
[Else
Statement 2
End If
Else
body-of-else]
End If
Select-Case Statement
Syntax:
It repeats a group of statements for each element in a collection. This loop is used for
accessing and manipulating all elements in an array or a VB.Net collection.
Syntax:
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
3. Do..Loop Structures
a. Do While..Loop :
Do While loop is an entry controlled loop in which the condition is placed at the
entry point. This statement executes the statements specified in the body of the loop till
the condition evaluates to true. The loop may not be executed at all the if the condition is
initially false.
Syntax:
Do While<condition or boolean expression>
‘ One or more VB Statements
Loop
b. Do..Loop While
Do Loop While is an exit controlled loop as the condition is placed at exit
point. The body of the loop is going to be executed at least once whether the condition
evaluates to true or false. Loop is executed as long as the result of the condition remains
true.
Syntax:
Do
One or more VB Statements
Loop While <condition or Boolean Expression>
c. Do..Until Loop
Do Until loop is an entry controlled loop in which the condition is placed at
the entry point. This statement executes the statements specified in the body of the loop
till the condition evaluates to false. The loop may not be executed at all the if the
condition is initially true.
Syntax:
Do Until <condition or boolean expression>
SHASHI RAJ, BMSCW /Page 31
VB.Net Programming
In VB.NET, string is a sequential collection of characters that is called a text. The String
keyword is used to create a string variable that stores the text value. The name of the
string class is System.String that contains the various function of string.
The following are the different ways to declare and initialize the string variable using the
String keyword in the VB.NET programming language
In the above declaration of string, we have defined the string variable with
string keyword and initialize string variable with value based on our requirements.
Lists
The List class is used to store generic types of collections objects. By using a generic
class on the list, we can store one type of object. The List size can be dynamically
different depending on the need of the application, such as adding, searching or inserting
elements into a list.
Property Description
name
Capacity It is used to obtain or set a number that indicates the number of elements
can be placed in a list.
The following are the methods of VB.NET List class for performing various operations
like add, search, remove, sort.
Method Description
Add As the name represents, the Add() method is used to add an object at the
end of the List
AddRange It is used to add the elements of the specified collection to the end of the
List.
Contains It is used to validate whether the specified object exists in the List or not.
CopyTo A CopyTo() method is used to copy all records of a list into a one-
dimensional array.
Find A Find() method is used to search for a specified element from a list that
matches the defined state and returns the first occurrence.
FindAll A FindAll() method is used to fetch all the elements from a list that
matches the condition defined by the specified predicate.
InsertRange It is used to insert all elements of a specified collection in a list start from a
specified location.
Remove By using the Remove() method, we can delete a specified element from the
list.
RemoveAt By using the RemoveAt() method in a list, we can delete an element from
the specified location in a list.
Reverse The Reverse() method is used to reverse the order list of elements.
ToArray It is used to copy all the elements of the list to a new array object.
Validation control
Validation controls are used to validate the data of an input control. If the data does not
pass validation, it will display an error message to the user. It is very-very useful in
client side validation.
Validation in database
Validation is the name given to the process whereby the information entered in the
database is checked to ensure that it makes sense. For example, you can use validation to
check that only numbers between 0 and 100 are entered in a percentage field, or only
Male or Female is entered in a sex field.
Uses of validation
The most basic use of validation functions is to ensure that documents are properly
formed to fit your application’s expectations. Without validation, you need to check for
the existence of all fields on a document that your Map Reduce or user-interface code
needs to function.
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don’t get stored.
ASP.NET provides the following validation controls:
Required Field Validator,
RangeValidator,
CompareValidator.
Procedures
A procedure is a group of statements that together perform a task when called. After the
procedure is executed, the control returns to the statement calling the procedure. VB.Net
has two types of procedures:
Functions
Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.
Functions
Defining a Function
The Function statement is used to declare the name, parameter and the body of a
function. The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
Modifiers: specify the access level of the function; possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding
overloading, overriding, sharing, and shadowing.
FunctionName: indicates the name of the function
ParameterList: specifies the list of the parameters
ReturnType: specifies the data type of the variable the function returns
Param Arrays: At times, while declaring a function or sub procedure, you are not sure of
the number of arguments passed as a parameter.
A function is similar to a normal procedure but the main purpose of the function is to
accept a certain input from the user and return a value which is passed on to the main
program to finish the execution. There are two types of functions, the built-in functions
(or internal functions) and the functions created by the programmers.
Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is:
Where,
Modifiers: specify the access level of the procedure; possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding
overloading, overriding, sharing, and shadowing.
values of the actual parameters are copied into them. So, the changes made to the
parameter inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword.
In VB.Net, you declare the reference parameters using the ByRef keyword.
Multiple Forms
VB.Net allows working with multiple forms. Every form in Visual Basic.Net is known
as windows. A Windows application can either be a Single Form application or multiple
form application.
Many times we want to add new forms to our project. We can add a new form to
the project by selecting Project->Add New Item from the main menu which
displays a window which has many items to add to your project.
Select Windows Form from that window and click on Add button to add a new
form to the project.
We can also add a new form from the Solution Explorer. To add a new form from
the Solution Explorer, right-click on the project name in Solution Explorer and
Select Add->Windows Form which again displays a window select Windows
Form and click on Add button.
Now you have to make some changes if you want to display the form which you
added when you run the application. For this right-click on the project name
in Solution Explorer select Properties which displays a Window.
On this window click the drop-down box named as Startup Form. By this you can
able to see each and every form of your project.
Now which form you want to displayed when you run the application select that
form and run your application. When you run the application, the form you
assigned as Startup Form will be displayed.
In visual Basic .NET we can work with multiple forms. For example, take three forms in
your application Form1, Form2 and Form3. Now drag a buttons form the toolbox
on Form1 andForm2. Now we want to open Form2 when a button on the Form1 is
clicked and when we clicked the button on Form2, Form3 will displayed. Double click
on Button1 on Form1 and place the code given below in the click event of the button.
Public Class Form1
After that, Double click on Button1 on Form2 and place the code given below in the
click event of the button.
Public Class Form2
Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They can
contain global (available to the whole application) or module-level declarations of
variables, constants, types, external procedures, and global procedures.
Menu Control
A menu is used as a menu bar in the Windows form that contains a list of related
commands, and it is implemented through MenuStrip Control. The Menu control is also
known as the VB.NET MenuStrip Control.
Properties Description
CanOverflow The CanOverflow property is used to authenticate whether the
control supports overflow functionality by setting values in the
MenuStrip control.
Stretch The Stretch property is used to obtain a value that specifies whether
the menustrip stretches from end to end in the MenuStrip control.
GripStyle The GripStyle property obtains or sets the visibility of the grip that
uses the reposition of the menu strip control.
ShowItemToolTips It is used to obtain or set the value that determines if the ToolTips
are displayed for the MenuStrip Control.
DefaultSize The DefaultSize property is used to get the default horizontal and
vertical dimension of the MenuStrip in pixel when it is first created.
Method Description
CreateAccessibilityInstance() It is used to create a new accessibility instance for the
MenuStrip Control.
ProcessCmdKey() The ProcessCmdKey method is used to process the
command key in the MenuStrip Control.
CreateDefaultItem() The CreateDefaultItem method is used to create a
ToolStripMenuItem with the specified text, image, and
event handlers for the new MenuStrip.
OnMenuActivate() It is used to initiate the MenuActivate event in the
MenuStrip control.
OnMenuDeactivate() It is used to start the MenuDeactivate event in the
MenuStrip control.
Events Description
MenuActivate When a user uses a menu bar control with a mouse or keyboard, a
MenuActivate event occurs.
MenuDeactivate The MenuDeactivate event occurs when the MenuStrip control is
deactivated in the Windows form.
ARRAYS
Array declarations in Visual Basic .NET are similar in Visual Basic.net and
other languages. For example, here is a declaration of an Integer array that
has five elements:
Dim a(4) As Integer
The literal 4 in this declaration specifies the upper bound of the array.
All arrays in Visual Basic .NET have a lower bound of 0, so this is a
declaration of an array with five elements, having indexes 0, 1, 2, 3, and 4.
The previous declaration is of a variable named a, which is of type "array
of Integer." Array types implicitly inherit from the .NET Framework's
Array type (defined in the System namespace) and, therefore, have access to
the methods defined in that type.
Multidimensional Arrays
In VB.NET, a multidimensional array is useful for storing more than one dimension in a
tabular form, such as rows and columns. The multidimensional array support two or
three dimensional in VB.NET.
Declaration of Multidimensional Array
Declaration of two-dimensional array
Dim twoDimenArray As Integer( , ) = New Integer(3, 2) {}
Or
Dim arr(5, 3) As Integer
Representation of Three Dimensional array
Dim arrThree(2, 4, 3) As Integer
Or
Dim arr1 As Integer( , , ) = New Integer(5, 5, 5) { }
Fixed-Size Arrays
A fixed-size array holds a fixed number of elements. This means that you must define
the number of elements that it will hold during its definition. Suppose you need an array
to hold only 3 student names.
You can define and initialize the array as follows:
Dim students(0 to 2) As String
students(0) = "John"
students (1) = "Alice"
students (2) = "Antony"
We began by declaring a string array named students. The 0 to 2 declares that the array
will store elements from its index 0 to index 2, meaning we will have 3 elements in total.
To add elements to the array, we have used the array name and specified the index at
which the element will be stored. For example, the name John will be stored at index 0
of the array, meaning that it will form the first element of the array. Antony will be the
last element of the array.
Static array:
Array is dimensioned during design time.
The timer control is a looping control used to repeat any task in a given time interval. It
is an important control used in Client-side and Server-side programming, also in
Windows Services.
Properties Description
Name The Name property is used to set the name of the control.
Enabled The Enables property is used to enable or disable the timer control. By
default, it is True.
Interval An Interval property is used to set or obtain the iteration interval in
milliseconds to raise the timer control's elapsed event. According to the
interval, a timer repeats the task.
AutoReset The AutoReset property is used to obtain or set a Boolean value that
determines whether the timer raises the elapsed event only once.
Events Events property are used to get the list of event handler that is
associated with Event Component.
CanRaiseEvents It is used to get a value that represents whether the component can raise
an event.
Events Description
Disposed When control or component is terminated by calling the Dispose method, a
Dispose event occurs.
Elapsed When the interval elapses in timer control, the Elapsed event has occurred.
Tick A tick event is used to repeat the task according to the time set in the Interval
property. It is the default event of a timer control that repeats the task between
the Start() and Stop() methods.
Methods Description
BeginInt() The BeginInt() method is used to start run time initialization of a timer
control used on a form or by another component.
Dispose() The Dispose() method is used to free all resources used by the Timer
Control or component.
Dispose(Boolean) It is used to release all resources used by the current Timer control.
Close() The Close() method is used to release the resource used by the Timer
Control.
Start() The Start() method is used to begin the Timer control's elapsed event
by setting the Enabled property to true.
EndInt() The EndInt() method is used to end the run time initialization of timer
control that is used on a form or by another component.
Stop() The Stop() method is used to stop the timer control's elapsed event by
setting Enabled property to false.
File Handling
A file is a collection of data stored in a disk with a specific name and a directory path.
When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path.
There are two main streams: the input stream and the output stream. The input stream is
used for reading data from file (read operation) and the output stream is used for writing
into the file (write operation).
VB.Net I/O Classes
The System.IO namespace has various classes that are used for performing various
operations with files, like creating and deleting files, reading from or writing to a file,
closing a file, etc.
The following table shows some commonly used non-abstract classes in the System.IO
namespace −
FileMode The FileMode enumerator defines various methods for opening files. The
members of the FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
Create − It creates a new file.
CreateNew − It specifies to the operating system that it should create
a new file.
Open − It opens an existing file.
OpenOrCreate − It specifies to the operating system that it should
open a file if it exists, otherwise it should create a new file.
Truncate − It opens an existing file and truncates its size to zero
bytes.
FileAccess FileAccess enumerators have members: Read, ReadWrite and Write.
EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. An exception
is a response to an exceptional circumstance that arises while a program is running, such
as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords:
Try, Catch,Finally and Throw.
Try: A Try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more Catch blocks.
Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.
Throw: A program throws an exception when a problem shows up. This is done
using a Throw keyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a
combination of the Try and Catch keywords. A Try/Catch block is placed around the
code that might generate an exception. Code within a Try/Catch block is referred to as
protected code, and the syntax for using Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Some of the exception classes derived from the System.Exception class are
the System.ApplicationException andSystem.SystemException classes.
The System.SystemException class is the base class for all predefined system
exception.The following table provides some of the predefined exception classes
derived from the Sytem.SystemException class:
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of
try and catch blocks. Using these blocks the core program statements are separated from
the error-handling statements.These error handling blocks are implemented using
the Try, Catch and Finallykeywords
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
Events
Events are basically a user action like key press, clicks, mouse movements, etc., or
some occurrence like system generated notifications. Applications need to respond to
events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all
are examples of events. An event is an action that calls a function or may cause another
event.
Mouse events
Keyboard events
MouseHover - it occurs when the mouse pointer hovers over the control
MouseMove - it occurs when the mouse pointer moves over the control
MouseUp - it occurs when the mouse pointer is over the control and the mouse
button is released
MouseWheel - it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following
properties:
KeyDown - occurs when a key is pressed down and the control has focus
KeyPress - occurs when a key is pressed and the control has focus
KeyUp - occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of
typeKeyEventArgs. This object has the following properties:
Modifiers - it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
The event handlers of the KeyDown and KeyUp events get an argument of type
KeyEventArgs. This object has the following properties:
The data residing in a data store or database is retrieved through the data provider.
Various components of the data provider retrieve data for the application and update
data.
An application accesses data either through a dataset or a data reader.
Datasets store data in a disconnected cache and the application retrieves data from it.
Data readers provide data to the application in a read-only and forward-only mode.
1 Connection
This component is used to set up a connection with a data source.
2 Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete
or modify data in a data source.
3 DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-
only mode.
4 DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a
database through a data adapter. It retrieves data from a database into a dataset and
updates the database. When changes are made to the dataset, the changes in the
database are actually done by the data adapter.
The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet −
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a data set.
3 Extended Properties
It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the
DataRow and DataColumn objects. The DataTable objects are case-sensitive.
5 DataRelation
6 DataRowCollection
It contains all the rows in a DataTable.
7 DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching,
editing and navigation.
8 PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and
methods are used to retrieve, evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new row and the Add method
adds a row to the table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a DataTable.
The Command object enables access to database commands to return data, modify data,
run stored procedures, and send or retrieve parameter information.
Delete Command – reference to a command for deleting rows from the data store.
The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination.
This object provides a connection oriented access to the data records in the database.
These objects are suitable for read-only access, such as populating a list and then
breaking the connection.
Important Classes in ADO.NET
1. Connection Class
2. Command Class
3. DataReader Class
4. DataAdaptor Class
5. DataSet.Class
1. Connection Class
In ADO.NET, we use these connection classes to connect to the database. These
connection classes also manage transactions and connection pooling.
2. Command Class
The Command class provides methods for storing and executing SQL statements and
Stored Procedures. The following are the various commands that are executed by the
Command Class.
ExecuteReader: Returns data to the client as rows. This would typically be an SQL
select statement or a Stored Procedure that contains one or more select statements.
This method returns a DataReader object that can be used to fill a DataTable object or
used directly for printing reports and so forth.
ExecuteNonQuery: Executes a command that changes the data in the database, such
as an update, delete, or insert statement, or a Stored Procedure that contains one or
more of these statements. This method returns an integer that is the number of rows
affected by the query.
ExecuteScalar: This method only returns a single value. This kind of query returns a
count of rows or a calculated value.
ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000
database using an XML stream. Returns an XML Reader object.
3. DataReader Class
The DataReader is used to retrieve data. It is used in conjunction with the Command
class to execute an SQL Select statement and then access the returned rows.
4. DataAdapter Class
The DataAdapter is used to connect DataSets to databases. The DataAdapter is most
useful when using data-bound controls in Windows Forms, but it can also be used to
provide an easy way to manage the connection between your application and the
underlying database tables, views and Stored Procedures.
5. DataSet Class
The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of
DataTable objects. In turn each object contains a collection of DataColumn and
DataRow objects. The DataSet also contains a Relations collection that can be used to
define relations among Data Table Objects.
Features of ADO.NET :
Interoperability- We know that XML documents are text-based formats. So, one can
edit and edit XML documents using standard text-editing tools. ADO.NET uses XML
in all data exchanges and for internal representation of data.
Maintainability- ADO.NET is built around the idea of separation of data logic and
user interface. It means that we can create our application in independent layers.
Programmability (Typed Programming): It is a programming style in which user
words are used to construct statements or evaluate expressions.
For example: If we want to select the “Marks” column from “Kawal” from the
“Student” table, the following is the way to do so:
DataSet.Student("Kawal").Marks;
Performance- It uses disconnected data architecture which is easy to scale as it
reduces the load on the database. Everything is handled on the client-side, so it
improves performance.
Scalability- It means meeting the needs of the growing number of clients, which
degrading performance. As it uses disconnected data access, applications do not retain
database lock connections for a longer time. Thus, it accommodates scalability by
encouraging programmers to conserve limited resources and allow users to access data
simultaneously.
1. DataSet
Dataset is connection-less oriented, that means whenever we bind data from the database it
connects indirectly to the database and then disconnected. It has read/write access to data
tables. It supports both forward and backward scanning of data.
DataSet is a container of one or more DataTable. More often than not, it will just contain one
table, but if you do a query with multiple SELECT statements, the DataSet will contain a table
for each.
You have to be careful about how much data you pull into a DataSet because this is an in-
memory representation. You can Fill a DataSet using the Fill() method of a DataAdapter.
2. DataReader
DataReader is connection-oriented, that means whenever we bind data from the database it
must require a connection and after that disconnected from the connection. It has read-only
access, we can’t do any transaction on them. It supports forward-only scanning of data, in other
words, you can’t go backward.
DataReader fetches one row at a time so very less network cost as compare to DataSet(that
fetches all the rows at a time). It is scalable to any number of records, at least in terms of
memory pressure, since it only loads one record at a time. One typical way to get a DataReader
is by using the ExecuteReader() method of a DbCommand.
3. DataAdapter
DataAdapter is an ADO.NET Data Provider. DataAdapter can perform any SQL operations
like Insert, Update, Delete, Select in the Data Source by using SqlCommand to transmit
changes back to the database.
DataAdapter provides communication between the Dataset/DataTable and the Datasource. We
can use the DataAdapter in combination with the DataSet/DataTable objects. These two objects
combine to enable both data access and data manipulation capabilities.
4. DataView
Generally, we use DataView to filter and sort DataTable rows. So we can say that DataView is
like a virtual subset of a DataTable. This capability allows you to have two controls bound to
the same DataTable, but showing different versions of the data.
For example, one control may be bound to a DataView showing all of the rows in the table,
while a second may be configured to display only the rows that have been deleted from the
DataTable. The DataTable also has a DefaultView property that returns the default DataView for
the table.
Generics
A generic type is a single programming element that adapts to perform the same
functionality for a variety of data types. When you define a generic class or procedure,
you do not have to define a separate version for each data type for which you might want
to perform that functionality.
For example, you might want to create and use a queue class that operates on a specific
data type such as String.
You can declare such a class from System.Collections.Generic.Queue<T>, as the
following example shows.
You can now use stringQ to work exclusively with String values. Because stringQ is
specific for String instead of being generalized for Object values, you do not have late
SHASHI RAJ, BMSCW /Page 58
VB.Net Programming
binding or type conversion. This saves execution time and reduces run-time errors.
A generic type serves as a basis for declaring several different programming elements,
each of which operates on a specific data type. The alternatives to a generic type are:
Type Safety. Generic types enforce compile-time type checking. Types based
on Object accept any data type, and you must write code to check whether an input
data type is acceptable. With generic types, the compiler can catch type mismatches
before run time.
Performance. Generic types do not have to box and unbox data, because each one
is specialized for one data type. Operations based on Object must box input data
types to convert them to Object and unbox data destined for output. Boxing and
unboxing reduce performance.Types based on Object are also late-bound, which
means that accessing their members requires extra code at run time. This also
reduces performance.
Code Consolidation. The code in a generic type has to be defined only once. A set
of type-specific versions of a type must replicate the same code in each version,
with the only difference being the specific data type for that version. With generic
types, the type-specific versions are all generated from the original generic type.
Code Reuse. Code that does not depend on a particular data type can be reused
with various data types if it is generic. You can often reuse it even with a data type
that you did not originally predict.
IDE Support. When you use a constructed type declared from a generic type, the
integrated development environment (IDE) can give you more support while you
are developing your code. For example, IntelliSense can show you the type-specific
options for an argument to a constructor or method.
Collections
Collection classes are specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes
implement the same interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to
elements and accessing a list of items on the basis of an index, etc. These classes create
collections of objects of the Object class, which is the base class for all data types in
VB.Net.
Various Collection Classes and Their Usage
The following are the various commonly used classes of
the System.Collection namespace. Click the following links to check their details.
Object oriented programming is a concept that was created because of the need to overcome
the problems that were found with using structured programming techniques. While structured
programming uses an approach which is top down, OOP uses an approach which is bottom up.
Traditionally, programming has placed an emphasis on logic and actions. Object oriented
programming has taken a completely different direction, and will place an emphasis on objects
and information. With object oriented programming, a problem will be broken down into a
number of units. These units are called objects. The foundation of OOP is the fact that it will
place an emphasis on objects and classes. In Object-Oriented programming a program is
divided into object and these object can communicate with each other through functions.
Concepts of OOP:
Objects
Classes
Data Abstraction
Encapsulation
Polymorphism
Inheritance
Objects
Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one
instance of an object. Each instance of an object can hold its own relevant data. An Object is a
collection of data members and associated member functions also known as methods. When a
program is executed, objects interact with each other by sending messages.
SHASHI RAJ, BMSCW /Page 61
VB.Net Programming
Classes
Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represent a set of individual
objects. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects becomes functions of the class and is referred to as Methods.
Data Abstraction
Data Abstraction increases the power of programming language by creating user defined data
types. Data Abstraction also represents the needed information in the program without
presenting the details. Classes use the concept of abstraction and are defined as a list of
abstract attributes.
Encapsulation
Data Encapsulation combines data and functions into a single unit called Class. When using
Data Encapsulation, data is not accessed directly; it is only accessible through the functions
present inside the class. Data Encapsulation enables the important concept of data hiding
possible.
Polymorphism
Poly means many and morph means form. Thus, polymorphism refers to being able to use
many forms of a type without regard to the details. It is the characteristic of being able to
assign a different meaning specifically, to allow an entity such as a variable, a function, or an
object to have more than one form. In Polymorphism objects behaves differently depending on
their data types.
Inheritance
End Class
End Class
Derived classes inherit, and can extend the methods, properties and events of the base
class. With the use of inheritance we can use the variables, methods, properties, events
etc, from the base class and add more functionality to it in the derived class.
Imports System. Console
Module Module1
Sub Main()
Dim Obj As New Subclass()
WriteLine(Obj.sum())
Read()
End Sub
End Module
End Class
End Class
Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a
Dynamic Link Library (DLL) and used as any other ASP.NET server control. They
could be created in either of the following way:
By deriving a custom control from an existing control
By composing a new custom control combing two or more existing controls.
By deriving from the base control class.
Crystal Reports is the standard reporting tool for Visual Studio .NET used to display
data of presentation quality. You can display multiple-level totals, charts to analyze data,
and much more in Crystal Reports. Creating a Crystal Report requires minimal coding
since it is created in Designer interface. It is available as an integrated feature of
Microsoft Visual Studio .NET, Borland Delphi, and C#Builder.
1. Rapid report development since the designer interface would ease the coding work
for the programmer.
2. Can extend it to complicated reports with interactive charts and enhance the
understanding of the business model
3. Exposes a report object model, can interact with other controls on the ASP.NET Web
form
4. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls,
.html and .rtf
Implementation Models
Crystal Reports need database drivers to connect to the data source for accessing data.
Crystal Reports in .net support two methods to access data from a data source:
When this model is used to access data from the data source, the database driver
directly retrieves the data from the data source. This model does not require the
developer to write code for creating a connection and retrieving data from the data
source. It is the Crystal report that manages the SQL commands for connecting by using
the specified driver
SHASHI RAJ, BMSCW /Page 64
VB.Net Programming
When this model is used to access data from data source, the developer writes the code
to connect to the data source and retrieve data. The data from the data source is cached
in dataset and multiple crystal reports accesses data from the dataset. The performance
can be optimized in this manner by using connection sharing and manually limiting the
number of records that are passed on to the report.
Crystal Report Designer can load reports that are included into the project as well as
those that are independent of the project.
Strongly-typed Report
When you add a report file into the project, it becomes a "strongly-typed" report. In this
case, you will have the advantage of directly creating an instance of the report object,
which could reduce a few lines of code, and cache it to improve performance. The
related .vb file, which is hidden, can be viewed using the editor's "show all files" icon in
the Solution Explorer.
Un-Typed Report
Those reports that are not included into the project are "un-typed" reports. In this case,
you will have to create an instance of the Crystal Report Engine's "ReportDocument "
object and manually load the report into it.
Global Scope: A variable declared in the main VB.NET body. Accessible from
any part of the code and any kind of scope.
Local Scope: A variable declared in a function or method. Due to encapsulation,
this variable can only be accessed in the function or method in which it was
declared in.
You can declare variables in three different settings in VB.NET classes. Each of one
these have its own protection level which determines what can access it.
Public: Equivalent to the Global Scope. Can be accessed from any part of the
code.
Private: Equivalent to the Local Scope. Can only be accessed within the method it
was declared in.
Protected: Similar to private variables, with one key difference. If a child class
inherits a class with protected variables, the child class will be able to access these
protected variables.
MDI stands for Multiple Document Interface applications that allow users to work with
multiple documents by opening more than one document at a time. Whereas, a Single
Document Interface (SDI) application can manipulate only one document at a time.
The MDI applications act as the parent and child relationship in a form. A parent form is
a container that contains child forms, while child forms can be multiple to display
different modules in a parent form.
1. MidParent: The MidParent property is used to set a parent form to a child form.
2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the
current child form.
3. IsMdiContainer: The IsMdiContainer property set a Boolean value to True that
represents the creation of a form as an MDI form.
4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the
parent or main form.
5. Controls: It is used to get the reference of control from the child form.
Let's create a program to display the multiple windows in the VB.NET Windows Forms.
Built-in Functions
VB.Net has many built-in functions for manipulating text and carrying out mathematical
operations, as well as the ability to format data in both standard and user-defined styles. We start
by looking at two functions that are both frequently used and at the same time relatively easy to
get to grips with - the MsgBox() function and the InputBox() function. We will then look at some
of the more commonly-used string-handling and math functions
MsgBox() function
The MsgBox() function displays a message in a pop-up message box. The user is expected to
respond by clicking on a button in order to be able to continue. The format of the statement used
to invoke a message box is as follows:
returnVal = MsgBox (prompt, styleVal, title)
The prompt parameter is a string value (either a string literal or a string variable) that supplies
the message to be displayed. The styleVal parameter is either an integer style value from 0 to 5, or
a named constant that can be used instead of the corresponding integer value, that determines
which command buttons will appear on the message box. The title parameter is another string
literal or string variable that supplies the title for the message box.
0 vbOkOnly OK
4 vbYesNo Yes, No
InputBox() function
The InputBox() function displays a pop-up input box into which the user can type a message. The
user is expected to enter their message, then click on a button ("Cancel" or "OK") in order to
continue. The format of the statement used to invoke an input box is as follows:
The returnString returned by the InputBox() function is the text entered by the user.
The prompt parameter is a text string (either a string literal or a string variable) that prompts the
user to enter some information. The title parameter is another string literal or string variable that
supplies the title for the input box. The defaultText parameter can be used to enter default content
in the input box (although it would probably be left blank in most cases).
The xpos and ypos parameters specify the x and y coordinates for the input box on screen.
String Functions
String Functions
Function Description
Mid (str, pos, n) Returns n characters from the text string referred to by str, starting
at character position pos.
Microsoft.VisualBasic.left Returns the n left-most characters from the text string referred to
(str, n) by str.
Microsoft.VisualBasic.right Returns the n right-most characters from the text string referred to
(str, n) by str.
Trim (str) Removes the white space (if any) at either end of the text string
referred to by str, and returns the result.
LTrim (str) Removes the white space (if any) at the left-hand end of the text
string referred to by str, and returns the result.
RTrim (str) Removes the white space (if any) at the right-hand end of the text
string referred to by str, and returns the result.
InStr (n, str1, str2) Looks for an occurrence of the substring str2 within the string str1,
starting at character position n. If successful, the function returns
the character position at which the substring is found (or zero if the
substring cannot be found).
UCase (str) Converts the string referred to by str to all upper-case characters,
and returns the result.
LCase (str) Converts the string referred to by str to all lower-case characters,
and returns the result.
Chr (charCode) Returns the ASCII character corresponding to the 8-bit character
code charCode (note – some characters are non-printing characters,
and will not be visible on screen).
Asc (character) Returns the 8-bit ASCII character code corresponding to character.
Mathematical functions
Maths Functions
Function Description
Math.Sqrt (n) Returns the square root of a number, n.
Math.Abs (n) Returns the absolute value of a number, n.
Math.Exp (n) Returns the exponential value of a number, n – i.e. e n.
Note: e = 2.71828182
Fix (n) Returns the integer part of a floating point number, n.
Int (n) Returns the integer part of a floating point number, n, for
positive numbers, or the next smallest integer value for
negative numbers.
Math.Log (n) Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value between 0 and 1.
Round (n,m) Rounds a number, n, up (or down) to m decimal places.
Example for Mathematical functions :
Private Sub MathClass_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
i = Math.Pow(5, 5)
MessageBox.Show("5 to the power= " & i)
i = Math.Sqrt(5)
MessageBox.Show("squre root of 5= " & i)
i = Math.Round(5.68743)
MessageBox.Show("round figure of 5.68743= " & i)
i = Math.Min(4, 7)
MessageBox.Show("minimum value in 4 and 7= " & i)
Dim j As Double
j = Math.Log(15)
MessageBox.Show("Log value of 15 = " & j)
j = Math.Sin(90)
MessageBox.Show("sin 90 = " & j)
End Sub