Date post: | 25-Oct-2014 |
Category: |
Documents |
Upload: | khaled-salahul-den |
View: | 112 times |
Download: | 1 times |
VB.NET2005
What is a Program?
An organized list of instructions that, when executed,
causes the computer to behave in a predetermined
manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients
(called variables) and a list of directions
(called statements) that tell the computer what to do with
the variables. The variables can represent
numeric data, text, or graphical images.
A programming language is an artificial
language that can be used to control the
behavior of a computer.
Source code is any series of statements written
in a programming language.
Computer Programming is the art of making a computer
do what you want it to do.(often shortened to programming
or coding) is the process of
writing, testing, and maintaining the source code
of computer programs.
What is Programming?
Event-driven Programming
In computer programming, Event-Driven
programming or event-based programming is a
programming paradigm in which the flow of the
program is determined by events
Ex:
sensor outputs or user actions (mouse clicks, key
presses) or messages from other programs or threads.
Object-oriented programming
Object-oriented programming (OOP) is a programming
model that uses "objects" – data structures consisting of data
fields and methods – and their interactions to design
applications and computer programs.
Programming techniques may include features such as,
1. Information hiding,
2. data abstraction,
3. encapsulation,
4. modularity,
5. polymorphism, and inheritance.
It was not commonly used in mainstream software application
development until the early 1990s. Many modern programming
languages now support OOP.
Why Object oriented approach?
A major factor in the invention of Object-Oriented approach is to remove some
of the flaws encountered with the procedural approach. In OOP, data is treated
as a critical element and does not allow it to flow freely. It bounds data closely
to the functions that operate on it and protects it from accidental modification
from outside functions. OOP allows decomposition of a problem into a number
of entities called objects and then builds data and functions around these
objects.
A major advantage of OOP is code reusability.
Some important features of Object Oriented programming are as follows:
• Emphasis on data rather than procedure
• Programs are divided into Objects
• Data is hidden and cannot be accessed by external functions
• Objects can communicate with each other through functions
• New data and functions can be easily added whenever necessary
• Follows bottom-up approach
Concepts of OOP:
1. Objects
2. Classes
3. Data Abstraction and
Encapsulation
4. Inheritance
5. Polymorphism
Objects
Objects are the basic run-time entities in an object-oriented system.
Programming problem is analyzed in terms of objects and nature of
communication between them. When a program is executed, objects
interact with each other by sending messages. Different objects can
also interact with each other without knowing the details of their data
or code.Dog(Object)
Attributes
• Skin color
• Eye color
• Height
• Weight
• Etc….
Behaviors
• Eat
• Bark
• Run
• Jump
• Etc….
Classes
A class is a collection of objects of similar type. Once a
class is defined, any number of objects can be created
which belong to that class.
MALE
SON
FATHER
Data Abstraction and Encapsulation
Abstraction refers to the act of representing essential features without
including the background details or explanations. Classes use the
concept of abstraction and are defined as a list of abstract attributes.
Storing data and functions in a single unit (class) is encapsulation.
Data cannot be accessible to the outside world and only those
functions which are stored in the class can access it.
ENCAPSULED
Formula + ingredients+
methods+ etc….
Inheritance
Inheritance is the process by which objects can acquire the properties of
objects of other class. In OOP, inheritance provides reusability, like, adding
additional features to an existing class without modifying it. This is
achieved by deriving a new class from the existing one. The new class will
have combined features of both the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An
operation may exhibit different behaviors in different instances.
The behavior depends on the data types used in the operation.
Polymorphism is extensively used in implementing Inheritance.
Shape
Triangle
Rectangle
Software Development Life Cycle
(SDLC)
A software development process is a structure
imposed on the development of a software product.
Synonyms include software life cycle and software
process. There are several models for such
processes, each describing approaches to a variety
of tasks or activities that take place during the
process.
SDLC is the Process of Developing
information system through Investigation,
Analysis, Design, Implementation and
maintenance
Software development life cycle model is also called as waterfall
model which is followed by majority of systems. This software
development life cycle process has the following seven stages in it
namely
1. System Requirements Analysis
2. Feasibility study
3. Systems Analysis and Design
4. Code Generation
5. Testing
6. Maintenance
7. Implementation
1. System Requirements Analysis:
The first essential or vital thing required for any software development is system. Also the system requirement may vary based on the software product that is going to get developed. So a careful analysis has to be made about the system requirement needed for the development of the product. After the analysis and design of the system requirement phase the system required for the development would be complete and the concentration can be on the software development process.
2. Feasibility study:
After making an analysis in the system requirement the next step is to make analysis of the software requirement. In other words feasibility study is also called as software requirement analysis. In this phase development team has to make communication with customers and make analysis of their requirement and analyze the system. By making analysis this way it would be possible to make a report of identified area of problem. By making a detailed analysis on this area a detailed document or report is prepared in this phase which has details like project plan or schedule of the project, the cost estimated for developing and executing the system, target dates for each phase of delivery of system developed and so on. This phase is the base of software development process since further steps taken in software development life cycle would be based on the analysis made on this phase and so careful analysis has to be made in this phase.
3. Systems Analysis and Design:
This is an important phase in system development .Here analysis is made on the design of
the system that is going to be developed. In other words database design, the design of the
architecture chosen, functional specification design, low level design documents, high level
design documents and so on takes place. Care must be taken to prepare these design
documents because the next phases namely the development phase is based on these
design documents. If a well structured and analyzed design document is prepared it would
reduce the time taken in the coming steps namely development and testing phases of the
software development life cycle.
4. Code Generation:
This is the phase where actual development of the system takes place. That is based on the
design documents prepared in the earlier phase code is written in the programming
technology chosen. After the code is developed generation of code also takes place in this
phase. In other words the code is converted into executable in this phase after code
generation.
5. Testing:
A software or system which is not tested would be of poor quality. This is because this is the phase where system developed would be tested and reports are prepared about bugs or errors in system. To do this testing phase there are different levels and methods of testing like unit testing, system test and so on. Based on the need the testing methods are chosen and reports are prepared about bugs. After this process the system again goes to development phase for correction of errors and again tested. This process continues until the system is found to be error free. To ease the testing process debuggers or testing tools are also available.
6. Maintenance:
After the testing phase is completely through and the system is found to be error free it is delivered to the customer. But no real system would be error free even then. This is because when the system gets executed in real user system scenarios there would be possibilities of lot of bugs and errors. This phase is called the maintenance phase and the errors in this are recorded and changes has to be made in the system accordingly and again testing phase comes into picture.
7. Implementation:
This is the final stage when the system gets into live.
The above software development process are all vital for a
system to get developed with quality and thus to
achieve customer satisfaction which is the main objective of
any software development process.
Objects
An object is an entity which has a state and a defined set
of operations which operate on that state. The state is
represented as a set of object attributes. The operations
associated with the object provide services to other
objects (clients) which request these services when some
computation is required.
Objects are created according to some object class
definition. An object class definition serves as a template
for objects. It includes declarations of all the attributes and
services which should be associated with an object of that
class.
Objects and object classes
• Objects are entities in a software system
which represent instances of real-world
and system entities
• Object classes are templates for objects.
They may be used to create objects
• Object classes may inherit attributes and
services from other object classes
Introduction
The .NET Platform provides the foundation for the next
generation of software that connect disparate systems,
information, devices, & users in a more unified and
professionalized way. It includes web services(XML) that
enables different Technologies to interoperate. It provides
software developers the tools and technology to quickly and
efficiently deliver business solutions that span multiple
applications and multiple client devices across many
organizations. It enables user to control how, when, and what
information is delivered to them.
What is the .NET Platform?
The .NET Framework is a set
of programming services
designed to simplify
application development in
the highly distributed
environment of the Internet.
The .NET Framework has
two main components : the
common language runtime
and the class library
How the .NET Framework Works
Terms & Definitions
Class - A Class is a named programming entity that comprise a common set of
methods, properties, and attributes. For Example, Form is one of the classes in
the System.Windows.Forms namespace that used to create Windows Forms
Namespace – A namespace identifies a collection of related classes and/or other
namespaces in the .NET Framework. Examples of namespaces are
System.Windows.Forms
Class library – The class library is a comprehensive object-oriented collection of
reusable classes that are organized by their functionality into hierarchical
namespaces.
Common Language Runtime – the common language runtime is the foundation
of the .NET Framework. In the .NET environment , programmers develop
applications in the .NET compatible language of their choice, the code is compiled
in to MSIL(Microsoft Intermediate language) and the runtime manages and runs
the compiled code.
Visual Studio .NET Integrated Development
Environment (IDE)
Menu
bar
Solution
Explorer
Property
WindowTool Box
The Form Window is central to developing Visual Basic applications.
It is where you draw your application.
The Toolbox is the selection menu
for controls used in your
application.
The Properties Window is used to
establish initial property values for
objects. The drop-down box at the top of
the window lists all objects in the current
form. Two views are available:
Alphabetic and Categorized. Under this
box are the available properties for the
currently selected object
Solution Explorer provides you with an
organized view of your projects and their
files as well as ready access to the
commands that pertain to them. A toolbar
associated with this window offers
commonly used commands for the item
you highlight in the list. To access Solution
Explorer, select Solution Explorer on the
View menu.
Class name list Method name list
Code editor allows user to write and maintain the code related to the
solution
Structure of a Visual Basic Application
Application (Project) is made up of:
Forms - Windows that you create for user interface
Controls - Graphical features drawn on forms to allow user interaction
(text boxes, labels, scroll bars, command buttons, etc.) (Forms and
Controls are objects.)
Properties - Every characteristic of a form or control is specified by a
property. Example properties include names, captions, size, color,
position, and contents. Visual Basic applies default properties. You
can change properties at design time or run time.
Methods - Built-in procedure that can be invoked to impart some
action to a particular object.
Event Procedures - Code related to some object. This is the code
that is executed when a certain event occurs.
General Procedures - Code not related to objects. This code must be
I invoked by the application.
Modules - Collection of general procedures, variable declarations, and
constant definitions used by application.
Steps in Developing Application
There are three primary steps involved in
building a Visual Basic application:
1. Draw the user interface
2. Assign properties to controls
3. Attach code to controls
Naming Objects
Control type prefix Example
Check box chk chkReadOnly
Combo box, drop-down list box cbo cboEnglish
Command button cmd cmdExit
Form frm frmEntry
Label lbl lblHelpMessage
List box lst lstPolicyCodes
ListView lvw lvwHeadings
Option button opt optGender
Picture box pic picVGA
RichTextBox rtf rtfReport
Text box txt txtLastName
Timer tmr tmrAlarm
Visual Basic Language
Keywords
The following table contains a listing of the Visual Basic .NET language
keywords. All language keywords are reserved.
AddHandler AddressOf Alias And
AndAlso Ansi As Assembly
Auto Boolean ByRef Byte
ByVal Call Case Catch
CBool CByte CChar CDate
CDec CDbl Char CInt
Class CLng CObj Const
CShort CSng CStr CType
Date Decimal Declare Default
Delegate Dim DirectCast Do
Double Each Else ElseIf
End Enum Erase Error
Event Exit False Finally
For Friend Function Get
GetType GoSub GoTo Handles
If Implements Imports In
Inherits Integer Interface Is
Let Lib Like Long
Loop Me Mod Module
MustInherit MustOverride MyBase MyClass
Namespace New Next Not
Nothing NotInheritable NotOverridable Object
On Option Optional Or
OrElse Overloads Overridable Overrides
ParamArray Preserve Private Property
Protected Public RaiseEvent ReadOnly
ReDim REM RemoveHandler Resume
Return Select Set Shadows
Shared Short Single Static
Step Stop String Structure
Sub SyncLock Then Throw
To True Try TypeOf
Unicode Until Variant When
While With WithEvents WriteOnly
Xor #Const #ExternalSource #If...Then...#Else
#Region - & &=
* *= / /=
\ \= ^ ^=
+ += = -=
Variables
With Visual Basic, and most programming languages, what you are doing is
storing things in the computer's memory, and manipulating this store. If you
want to add two numbers together, you put the numbers into storage areas
and "tell" Visual Basic to add them up. But you can't do this without variables.
1. No more than 40 characters
2. They may include letters, numbers, and underscore
(_)
3. The first character must be a letter
4. You cannot use a reserved word (word needed by
Visual Basic)
Dim
Short for Dimension. It's a type of variable. You declare (or "tell" Visual
Basic) that you are setting up a variable with this word.
number1
This is a variable. In other words, our storage area. After the Dim word,
Visual Basic is looking for the name of your variable. You can call your
variable almost anything you like
As Integer
We're telling Visual Basic that the variable is going to be a number
(integer).
Number1 = 3
The equals sign is not actually an equals sign. The = sign means assign a
value of. In other words, here is where you put something in your variable.
We're telling Visual Basic to assign a value of 3 to the variable called
number1.
Now examine this:
Dim number1 As Integer
Dim number 2 As Integer
number1 = 3
number2 = 5
Data Type Size in Bytes Description
Byte 1 8-bit unsigned integer
Char 2 16-bit Unicode characters
Integer 4 32-bit signed integer
Double 8 64-bit floating point variable
Long 8 64-bit signed integer
Short 2 16-bit signed integer
Single 4 32-bit floating point variable
String Varies Non-Numeric Type
Date 8
Boolean 2 Non-Numeric Type
Object 4 Non-Numeric Type
Decimal 16 128-bit floating point variable
Data Types in VB .NET
Visual Basic Data Types
Data Type
Boolean
Integer
Long (Integer)
Single (Floating)
Double (Floating)
Currency
Date
Object
String
Variant
Suffix
None
%
&
!
#
@
None
None
$
None
There are three ways for a variable to be typed (declared):
1. Default
2. Implicit
3. Explicit
If variables are not implicitly or explicitly typed, they are assigned the variant
type
by default. The variant data type is a special type used by Visual Basic that
can contain numeric, string, or date data.
To implicitly type a variable, use the corresponding suffix shown above in
the data type table. For example,
Dim <Variable name> $ = "This is a string"
//creates a string variable, while
Dim <Variable name> % = 300
//creates an integer variable.
Variable Declaration
There are many advantages to explicitly typing variables. Primarily, we insure
all computations are properly done, mistyped variable names are easily spotted,
and Visual Basic will take care of insuring consistency in upper and lower case
letters used in variable names. Because of these advantages, and because it is
good programming practice, we will explicitly type all variables.
To explicitly type a variable, you must first determine its scope.
There are four levels of scope:
1. Procedure level
2. Procedure level, static
3. Form and module level
4. Global level
Within a procedure, variables are declared using the Dim statement:
Dim <Variable name> as Integer
Dim <Variable name> as Double
Dim <Variable name> , <Variable name> as String
Procedure level variables declared in this manner do not retain their value once
a procedure terminates.
To make a procedure level variable retain its value upon exiting the procedure,
replace the Dim keyword with Static:
Static <Variable name> as Integer
Static <Variable name> as Double
Form (module) level variables retain their value and are available to all
procedures within that form (module). Form (module) level variables are
declared in the declarations part of the general object in the form„s (module's)
code window.
The Dim keyword is used:
Dim <Variable name> as Integer
Dim <Variable name> as Date
Public level variables retain their value and are available to all procedures within
an application. Module level variables are declared in the declarations part of the
general object of a module's code window. (It is advisable to keep all Public
variables in one module.) Use the Public keyword:
Public <Variable name> as Integer
Public <Variable name> as Date
String Variables
What is a String? Actually a string is nothing more than text. And if we want
Visual Basic to store text we need to use the word "String". To set up a variable
to hold text we need to use As String and not As Integer. If the information we
want to store in our variables is a First Name and a Last Name, we can set up
two variables like this.
Dim FirstName As String
Dim LastName As String
Arrays
An array is a collection of values of the same data type. The values in an array are called
array elements. Array elements are accessed using a single name and an index number
representing the position of the element within the array.
An array is a standard structure for storing data in any programming language. Variables can
hold single entities, such as one number, one date, or one string and arrays can hold sets of
data of the same type (a set of numbers, a series of dates, and so on). An array has a name,
and the values stored in it can be accessed by an index.
Declaring Arrays
Unlike simple variables, arrays must be declared with the Dim (or
Public, or Private) statement followed by the name of the array and the
index of the last element in the array in parentheses for example:
Dim Ages(19) As Integer
Initializing Arrays
Just as we can initialize variables in the same line where we declare them, we
can initialize arrays too, with the following constructor:
Here´s an example that initializes an array of strings:
Dim names() As String ("john", "Sam","Hedric")
This statement is equivalent to the following statements, which declare an array
with two elements and then set their values:
Dim names(2) As String
names(O)="John"
names(1) ="Sam"
names(2) ="Hedric"
The number of elements in the curly brackets following the array´s declaration
determines the dimensions of the array, and we can´t add new elements to the
array without resizing it.
Multidimensional Arrays
Arrays can be multidimensional. Multidimensional arrays can be thought of as arrays-of-
arrays. For example, to visualize a two dimensional array we could picture a row of CD
racks. To make things easier, we can imagine that each CD rack could be for a different
artist. Like the CDs, the racks would be identifiable by number. Below we'll define a two
dimensional array representing a row of CD racks. The strings inside of the array will
represent album titles.
' Here we will define an array where the first dimension contains 2 elements and the
second dimension contains 4 elements
Dim cdRack(1,3) As String
' A CD rack for the Beatles
cdRack(0, 0) = "Rubber Soul"
cdRack(0, 1) = "Revolver"
cdRack(0, 2) = "The White Album"
cdRack(0, 3) = "Let It Be“
' A CD rack for the Rolling Stones
cdRack(1, 0) = "Sticky Fingers"
cdRack(1, 1) = "Beggars Banquet"
cdRack(1, 2) = "Let It Bleed"
cdRack(1, 3) = "Tattoo You"
0 1 2 3
0 Rubber Soul RevolverThe White
AlbumLet It Be
1Stickey
Fingers
Beggars
BanquetLet It Bleed Tatto You
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data.
An operator performs a function on one or more operands.
For example, we add two variables with the "+" addition operator and store the
result in a third variable with the "=" assignment operator like this:
int x + int y = int z.
The two variables (x ,y) are called operands. There are different types of
operators in Visual Basic
1. Arithmetic Operators
2. Concatenation Operators
3. Comparison Operators
4. Logical / Bitwise Operators
Operators
Operator Use
^ Exponentiation
-Negation (used to reverse the sign of the
given value, exp -intValue)
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve
calculation of numeric values. The table below summarizes them:
Dim x, y, z As Integer
x = 30
y = 20
z = x + y
MessageBox.Show(z)
z = x - y
MessageBox.Show(z)
z = x * y
MessageBox.Show(z)
z = x / y
MessageBox.Show(z)
Example
Operator Use
+ String Concatenation
& String Concatenation
Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two
concatenation operators, + and & as summarized below:
Example:
Dim str1, str2, str3, str4 As String
str1 = "Concatenation"
str2 = "Operators"
str3 = str1 + str2
MessageBox.Show(str3)
str4 = str1 & str2
MessageBox.Show(str4)
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to
Comparison Operators
A comparison operator compares operands and returns a logical
value based on whether the comparison is true or not. The table
below summarizes them:
Dim x, y As Integer
x = 10
y = 15
If x = y Then
MessageBox.Show ("x is Equal to y")
ElseIf x < y Then
MessageBox.Show("x is less than y")
ElseIf x > y Then
MessageBox.Show("x is greater than y")
End If
Example
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean
result. In short, logical operators are expressions which return a true or false
result over a conditional expression. The table below summarizes them:
The Not operator
The Not operator will return the opposite of the Boolean value, Not True will return False and
Not False will return True. See the example below:
Dim P As Boolean = False
MessageBox.Show(Not P)
The And operator
The And operator will check if two boolean values are true. Both needs to True or the And
operator won't return true. See the examples below:
Dim P, Q As Boolean
P = True
Q = False
MessageBox.Show(P And Q)
The Or operator
For the Or operator to return True, at least one of the values have to be True. If both are True
doesn't matter, it will also return True. Look at this example below:
Dim P, Q As Boolean
P = True
Q = False
MessageBox.Show(P Or Q)
The Xor operator
The Xor operator will return True if and only if one of the values are True. This means that the
different between Or and Xor is that if both values are True, Or will return True but Xor will
return False, See this example:
Dim P, Q As Boolean
P = False
Q = False
MessageBox.Show(P Xor Q)
Console Applications
Console Applications are command-line oriented applications that allow us to read characters from the
console, write characters to the console and are executed in the DOS version. Console Applications are
written in code and are supported by the System.Console namespace.
Example on a Console Application
Module Module1
Sub Main()
System.Console.Write("Welcome to Console Applications")
End Sub
End Module
The following code is example of a console application:
Run the code by selecting Debug->Start or Press Ctrl+F5
Commenting the Code
Comments in VB.NET begin with a single quote (') character and the
statements following that are ignored by the compiler. Comments are
generally used to specify what is going on in the program and also gives an
idea about the flow of the program. The general form looks like this:
'declaring an integer
Dim I as Integer
Breaking the Code to understand it
Visual Basic Module and Modules are designed to hold code. All the code
which we write should be within the Module.
Next line starts with Sub Main(), the entry point of the program.
The third line indicates that we are using the Write method of the
System.Console class to write to the console.
A function is a segment of code that accepts zero, one or more arguments and
returns a single result. Some
perform basic mathematical tasks. Others manipulate string data such as
converting text to uppercase or lowercase letters.
What is a Function ?
What is an Argument ?
An argument is a value you pass to a function so the function has data to
work with . Function names have parentheses at the end to hold the
function arguments. Even if a function has no arguments, the parenthesis
are required. Two intrinsic functions include message boxes and input
boxes
Selection Structure?
The If Then statement(or only If Statement) is a block of code that will
only be run if the specific condition is met and therefor will return True,
if the condition returns False the code will jump past the If block and
continue at "End If" which is the end of an If block. The syntax for and If
statement are:
If <condition> Then
'code to be executed if the condition are met
End If
If True Then
MessageBox.Show("Inside the If block")
End If
The If statement check if the condition is True, and here it is. This will
make the line(s) inside the If block to be executed. In this example a
messagebox will be shown. But if we change "True" to "False" in the
above code, the messagebox will not be showed since the code will
jump past the If block because the conditions where False.
Example
Dim x As Integer
x = 3
If x > 0 Then
MessageBox.Show("x is greater then 0")
End If
If Then Else Statement:
The opportunities doesn't end there. We can also create something called an If Then Else
statement. This works like an If Then Statement but it has two blocks of codes. If the condition
is met(True) the first block of code will be run. But instead of just jumping to the End If straight
away if the conditions aren't met(False) the second block of code is executed.
The syntax for an If Then Else Statement looks like this:
Code:
If <condition> Then
'code to be executed if the condition are met
Else
'code to be executed if the condition are NOT met
End If
Dim x, y, z As Integer
x = 1
y = 9
z = 14
If x < y And y < z Then
MessageBox.Show("x is smallest and z is largest")
Else
MessageBox.Show("The variables are not in size order")
End If
Example
If Then ElseIf Else Statement:
The ElseIf blocks is working exactly the same as an If block, the If block is the first one and then
it's followed by ElseIf blocks and at the end you can add a else block if you want. If the If block's
statement are True that block will be run and then the code will jump to the End If, however if it's
False it will test if the condition of the first ElseIf block is True, if this also is False it will go to the
second one etc. If all conditions are False and there's an Else block this will be executed.
Here's the syntax for the If Then ElseIf Else Statement:
If <condition> Then
'code to be executed if the condition are met
ElseIf <condition> Then
'code to be executed if the condition are met but no conditions above
Else
'code to be executed if none of the conditions are met
End If
Example
Dim x, y, z As Integer
x = 2
y = 5
z = 8
If x = 0 Then
MessageBox.Show("x is equals to 0")
ElseIf x < y And y < z Then
MessageBox.Show("x is smallest and z is largest")
ElseIf x = y And y = z Then
MessageBox.Show("all variables has the same value")
Else
MessageBox.Show("None of the conditions above are met")
End If
The select case statement is good to use when you want different blocks of code to be
executed depending on different values on one variable. If statements is good if you only
need to test one value
Anyway, to use a select case statement you have to create it by writing "Select Case" and
then the value you want to test. End the statement with "End Select". Could look something
like this:
Select Statement
Select Case <Value that intended to test>
End Select
Select Case myVariable
Case 1
MessageBox.Show("myVariable = 1")
Case 2
MessageBox.Show("myVariable = 2")
Case 3, 4
MessageBox.Show("myVariable = 3 or 4")
Case 5
MessageBox.Show("myVariable = 5")
Case Else
MessageBox.Show("myVariable is nether 1,2,3,4 or 5")
End Select
Example
More advanced Select Case Statements
To
When using some sort of values(Integers for example) you can add a whole
range of numbers to one case by using "[number] To [number]", like this:
Select Case myVariable
Case 0 To 5
MessageBox.Show("myVariable is
between 0 and 5")
Case 6 To 10
MessageBox.Show("myVariable is
between 6 and 10")
Case 11
MessageBox.Show("myVariable = 11")
End Select
Is
You can also add relational operators to your select case statement. Do this by replace
"Case [value]" with "Case Is [relational operator] [value]". Actually a select case statement
does always contains a relational operator, the is equals to operator (=) even though it's
hidden. This means that "Case Is = myValue" is the same as "Case myValue". Here comes
a little example on how to use it:
Select Case myVariable
Case Is > 0
MessageBox.Show("myVariable is
greater then 0")
Case Is < 0
MessageBox.Show("myVariable is less
then 0")
Case Else
MessageBox.Show("myVariable is
equals to 0")
End Select
Exercise
Part 1 - If statements
Start a new project. Add a textbox, a Label and a button to your new Form. Then write a programme that does the following: 1. Asks users to enter a number between 10 and 20. 2. The number will be entered into the Textbox. 3. When the Button is clicked, your Visual Basic code will check the number entered in the Textbox. 4. If it is between 10 and 20, then a message will be displayed. 5. The message box will display the number from the Textbox. 6. If the number entered is not between 10 and 20 then the user will be invited to try again, and whatever was entered in the Textbox will be erased
Part 2 - Select Case Statements
Add a Combo box and another button to your form. Create a list of items for your Combo Box. The list of items in your Combo box can be anything you like - pop groups, football teams, and favorite foods, anything of your choice. Then try the following: Use a select case statement to test what a user has chosen from your drop-down list. Give the user a suitable message when the button was clicked.
Looping Structure
The While Loop:
The while loop will continue with its loop as long a condition remains True. The
condition is tested at the beginning each time the loop will start a new turn. If the
condition isn't met at the beginning the loop won't even run once. The syntax of a
while loop looks as following:
Code:
While <condition>
'Code that will be run once per turn
End While
To show a simple example:
Dim X as Integer = 3
While X<300
X*=2
End While
Do While loop:
This type of loop has only one difference to the While loop more then the syntax.
The Do While loop will check the condition at the end instead of in the beginning.
This is actually pretty important. Here's the syntax anyway:
Do
'Code that will be run once per turn
Loop While <condition>
Example
Dim x As Integer
x = 10
Do
MessageBox.Show(x)
x+=1
Loop While x < 15
Do Until loop:
The Do While loop will continue if the condition are True and stop if the condition
are False. The Do Until loop does the opposite, it will continue if the condition are
False and stop if the condition are True. It will loop Until the condition are met.
The syntax of the Do Until loop and also an example of it:
Syntax Code:
Do
'Code that will be run once per turn
Loop Until <condition>
Example:
Code:
Dim X As Integer = 312
Do
X /= 10
MessageBox.show(x)
Loop Until X = 0
For Loops
The For loop will loop a certain amount of times and when it have looped so many times it will
stop. When declaring a For loop you give it a name just like you do when you declares a
variable.This is the syntax for declaring a For loop:
For <loop_name> As <type> = <start> To <end>
'code inside the loop
Next
Ex 01:
For i As Integer = 0 To 2
MessageBox.Show(i)
Next
Ex 02:
For i As Integer = 1 To 10 Step 3
MessageBox.Show(i)
Next
CBool - use this function to convert to Bool data type
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CShort - use this function to convert to Short data type
CStr - use this function to convert to String data type
Built-in Converting Function
MsgBox ( ) Function
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.
MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows:
MsgBox(Prompt, Style Value, Title)
The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box,. The Title argument will display the title of the message board.
The InputBox( ) Function
An InputBox( ) function will display a message box where the user can enter a value or a message in
the form of text. The format is
InputBox(Prompt, Title, default_text, x-position, y-position)
Prompt - The message displayed normally as a question asked.
Title - The title of the Input Box.
default-text - The default text that appears in the input field where users
can use it as his intended input or he may change to the message he wish to
key in.
x-position and y-position - the position or the coordinate of the input box.
Form Controls
A control is an object that can be drawn on to the Form to enable or enhance
user interaction with the application.
Examples of these controls, Textboxes, Buttons, Labels, Radio Buttons, etc.
All these Windows Controls are based on the Control class, the base class for
all controls. Visual Basic allows us to work with controls in two ways: at design
time and at runtime. Working with controls at design time means, controls are
visible to us and we can work with them by dragging and dropping them from
the Toolbox and setting their properties in the properties window. Working at
runtime means, controls are not visible while designing, are created
and assigned properties in code and are visible only when the application
is executed.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with
the Click Event. The Click event of Button looks like this in code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
'You place the code here to perform action when Button is clicked
End Sub
TextBox Control
This control looks like a box and accepts input from the user. The TextBox is based on the
TextBoxBase class which is based on the Control class. TextBoxes are used to accept input
from the user or used to display text. By default we can enter up to 2048 characters in a
TextBox but if the Multiline property is set to True we can enter up to 32KB of text. The image
below displays a Textbox.
TextBox Event
Private Sub TextBox1_TextChanged(ByVal sender
As System.Object, ByVal e As _System.EventArgs)
Handles TextBox1.TextChanged
End Sub
RichTextBox
RichTextBoxes are similar to TextBoxes but they provide some advanced features over the
standard TextBox. RichTextBox allows formatting the text, say adding colors, displaying
particular font types and so on.
RichTextBox Event
Private Sub RichTextBox1_TextChanged(ByVal sender
As System.Object, _
ByVal e As System.EventArgs) Handles
RichTextBox1.TextChanged
End Sub
Private Sub Italic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Italic.Click
RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's
'return property to SelectionStart which selects the text to format
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
'creating a new font object to set the font style
RichTextBox1.SelectionFont = ifont
'assigning the value selected from the RichTextBox the font style
End Sub
Private Sub Font color_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Fontcolor.Click
RichTextBox2.SelectionStart = RichTextBox2.Find("are")
'using the Find method to find the text "are" and setting it's return
'property to SelectionStart which selects the text
RichTextBox2.SelectionColor = Color.Blue
'setting the color for the selected text with SelectionColor property
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
RichTextBox3.SaveFile("hello.rtf")
'using SaveFile method to save text in a rich text box to hard disk
End Sub
Private Sub load_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load.Click
RichTextBox4.LoadFile("hello.rtf")
'using LoadFile method to read the saved file
End Sub
Label, LinkLabel
Label
Labels are those controls that are used to display text in other parts of the application. They
are based on the Control class.
Notable property of the label control is the text property which is used to set the text for the
label.
Working with Linked labels
Private Sub LinkLabel1_LinkClicked(ByVal sender As
System.Object, ByVal_
e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.google.com")
'using the start method of system.diagnostics.process class
'process class gives access to local and remote processes
End Sub
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False.
A checkbox is clicked to select and clicked again to deselect some option. When a checkbox
is selected a check (a tick mark) appears indicating a selection.
CheckBox Event
Private Sub CheckBox1_CheckedChanged(ByVal
sender As System.Object, _
ByVal e As System.EventArgs) Handles
CheckBox1.CheckedChanged
End Sub
Code to check a CheckBox's state using a button Event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
TextBox1.Text = "Checked"
Else
TextBox1.Text = "UnChecked"
End If
End Sub
RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead
of boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select and
deselect options but they allow us to choose from mutually exclusive options.
RadioButton Event
Private Sub RadioButton1_CheckedChanged(ByVal
sender As System.Object,_
ByVal e As System.EventArgs) Handles
RadioButton1.CheckedChanged
End Sub
Code to check a RadioButton's state Using a Button Event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
TextBox1.Text = "Selected"
Else
TextBox1.Text = "Not Selected"
End If
End Sub
ListBox
The ListBox control displays a list of items from which we can make a selection. We can
select one or more than one of the items from the list.
Button 1Button 2
Button 3TextBox 4
TextBox 1
TextBox 2
TextBox 3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
TextBox1.Text = ListBox1.SelectedIndex
TextBox2.Text = ListBox1.Items.Count
TextBox3.Text = ListBox1.SelectedItem
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button3.Click
ListBox1.Items.Clear()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
ListBox1.Items.RemoveAt(TextBox5.Text)
End Sub
ComboBox
ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing
field (TextBox) combined with a ListBox allowing us to select from the list or to enter new text.
ComboBox displays data in a drop-down style format.
TreeView
The tree view control is used to display a hierarchy of nodes (both parent, child). You can
expand and collpase these nodes by clicking them. This control is similar to Windows
Explorer which displays a tree view in it's left pane to list all the folders on the hard disk.
1
2
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
Label1.Text = e.Node.FullPath
End Sub
CheckedListBox
As the name says, CheckedListBox is a combination of a ListBox and a CheckBox. It displays a
ListBox with a CheckBox towards it's left.
Panel
Panels are those controls which contain other controls, for example, a set of radio buttons,
checkboxes, etc. Panels are similar to Groupboxes but the difference, Panels cannot display
captions where as GroupBoxes can and Panels can have scrollbars where as GroupBoxes can't. If
the Panel's Enabled property is set to False then the controls which the Panel contains are also
disabled.
GroupBox Control
As said above, Groupboxes are used to Group controls. GroupBoxes display a frame around them
and also allows to display captions to them which is not possible with the Panel control.
PictureBox Control
PictureBoxes are used to display images on them. The images displayed can be anything varying
from Bitmap, JPEG, GIF, PNG or any other image format files.
ToolTip, ErrorProvider
ToolTip
ToolTips are those small windows which display some text when the mouse is over a control
giving a hint about what should be done with that control. ToolTip is not a control but a
component which means that when we drag a ToolTip from the toolbox onto a form it will be
displayed on the component tray.
Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Do not leave this
blank")
End Sub
ErrorProvider Component
The ErrorProvider component provides an easy way to set validation errors. It allows us to set
an error message for any control on the form when the input is not valid. When an error
message is set, an icon indicating the error will appear next to the control and the error
message is displayed as Tool Tip when the mouse is over the control.
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e_
As System.EventArgs) Handles
Button1.Click
If TextBox1.Text = "" Then
ErrorProvider1.SetError(TextBox1, "Cannot
leave textbox blank")
Else
ErrorProvider1.SetError(TextBox1, "")
End If
End Sub
Menus
Menus allow us to make a selection when we
want to perform some action with the application,
for example, to format the text, open a new file,
print and so on. In VB .NET Main Menu is the
container for the Menu structure of the form.
Menus are made of Menu Item objects that
represent individual parts of a menu (like File-
>New, Open, Save, Save As etc).
The two main classes involved in menu handling
are, Main Menu and Menu Item. The Main Menu
class let's us assign objects to a form's menu
class and Menu Item is the class which supports
the items in a menu system. Menus like File,
Edit, Format etc and the items in those Menus
are supported by this Menu Item class. It's this
Menu Item's click event that makes these Menus
work. For a Menu Item to be displayed, we need
to add it to a Main Menu object.
Date Time Picker
Date Time Picker allows us to select date and time. Date Time Picker is based on the control class.
When we click on the drop-down arrow on this control it displays a month calendar from which we
can make selections. When we make a selection that selection appears in the textbox part of the
Date Time Picker. The image below displays the Date Time Picker.
Private Sub DateTimePicker1_ValueChanged(ByVal
sender As System.Object, ByVal e As
System.EventArgs) Handles
DateTimePicker1.ValueChanged
TextBox1.Text = DateTimePicker1.Text
End Sub
Month Calendar
The Month Calendar control allows us to select date. The difference between a Date Time
Picker and Month Calendar is, in Month Calendar we select the date visually and in Date Time
Picker when we want to make a selection we click on the drop-down arrow and select the date
from the Month Calendar which is displayed. The image below displays a Month Calendar
control.
Private Sub MonthCalendar1_DateChanged(ByVal
sender As System.Object, ByVal e As
System.Windows.Forms.DateRangeEventArgs)
Handles MonthCalendar1.DateChanged
TextBox4.Text
=MonthCalendar1.SelectionStart.ToLongDateString
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Timer1.Tick
Label1.Text = TimeOfDay
End Sub
The Timer control allows you to set a time interval to execute an event after that interval
continuously. It is useful when you want to execute certain applications after a certain
interval.
The Timer
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Timer1.Tick
Label1.Text = Format(Now, "dddd")
Label2.Text = Format(Now, "mm")
Label3.Text = Format(Now, "yyyy")
Label4.Text = System.DateTime.Now.ToString("dd-MMM-yyyy")
End Sub
Date Formatting
Creating a Simple Calculator
Creating User defined method to calculate totals
Private Sub CalculateTotals()
str2 = TextBox1.Text
Select Case calcFunc
Case "+"
str1 = str1 + str2
Case "-"
str1 = str1 - str2
Case "/"
str1 = str1 / str2
Case "*"
str1 = str1 * str2
End Select
TextBox1.Text = str1
inputStatus = True
End Sub
Declaring Variables
Dim str1 As Double
Dim str2 As Double
Dim calcFunc As String
Dim inputStatus As Boolean
Button Event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
If inputStatus = False Then
TextBox1.Text += Button1.Text
Else
TextBox1.Text = Button1.Text
inputStatus = False
End If
End Sub
Operation Button Events
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnAdd.Click
If TextBox1.Text.Length <> 0 Then
If calcFunc = "" Then
str1 = TextBox1.Text
TextBox1.Text = ""
Else
CalculateTotals()
End If
calcFunc = btnAdd.Text
End If
Clear Button Event
Private Sub Clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Clear.Click
TextBox1.Text = ""
str1 = 0
str2 = 0
calcFunc = "“
End Sub
Equal Button event
Private Sub Equal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Equal.Click
If TextBox1.Text.Length <> 0 And str1 <> 0 Then
CalculateTotals()
calcFunc = "“
End If
End Sub
Database Access
What is a database?
A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view,
Connection - Establishes a connection to a specific data source.
Data Provider?
A data provider in the .NET Framework serves as a bridge between an application and a
data source. A data provider is used to retrieve data from a data source and to resolve
changes to that data back to the data source.
Data Adapters?
Adapters are used to exchange data between a data source and a dataset.
A Dataset?
Represents a complete set of data including the tables that contain, order, and constrain the
data, as well as the relationships between the tables.
Introducing
ADO.NET
ADO.NET is the .NET platform’s new database technology, and it builds
on ADO (Active Data Objects).
ADO.NET provides DataSet and DataTable objects that are optimized for
moving disconnected sets of data across the Internet and intranets,
including through firewalls. At the same time, ADO.NET includes the
traditional connection and command objects, as well as an object called a
DataReader, (which resembles a forward-only, read-only ADO Record Set, in
case you’re familiar with ADO).
Together, these objects provide the best performance and throughput
for retrieving data from a database.
ADO.NET architecture
The ADO.NET Data Architecture
Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a
local copy of the relevant portions of the database. The DataSet is persisted in memory and
the data in it can be manipulated and updated independent of the database. When the use of
this DataSet is finished, changes can be made back to the central database for updating. The
data in DataSet can be loaded from any valid data source like Microsoft SQL server database,
an Oracle database or from a Microsoft Access database.
Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database.
A DataProvider is a set of related components that work together to provide data in an efficient
and performance driven manner. The .NET Framework currently comes with two
DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL
Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of
databases like Access and Oracle. Each DataProvider consists of the following component
classes:
The Connection object which provides a connection to the database
The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs
update
Attaching the code
Connecting to a Database
To access data in a database, you must first establish a connection using an ADO.NET
connection object. Multiple connection objects are included in the .NET Framework, such
as the OleDbConnection object (for working with the same OLE DB data providers you
would access through traditional ADO) and the SqlConnection object (for optimized
access to Microsoft SQL Server).To create an object variable of type OleDbConnection
and initialize the variable to a new connection, you could use a statement like this
Dim <Connection Name> As New OleDb.OleDbConnection()
Possible Parameters for ConnectionString
Parameter Description
Provider The name of the data provider (Jet, SQL, and so on)
to use.
Data
Source
The name of the data source (database) to connect to.
User ID A valid username to use when connecting to the data
source.
Password A password to use when connecting to the data
source.
SERVER The network name of the data source server.
1. Specify the ConnectionString property of your ADO.NET connection now by placing
the following statement in the Load event of your form:
<Connection Name>.ConnectionString = _
“Provider=Microsoft.Jet.OLEDB.4.0; Data Source=<Database Source>”
2. After the connection string is defined, a connection to a data source is established by
using the Open () method of the connection object. Add the following statement to the
Load event, right after the statement that sets the connection string:
<Connection Name>.Open()
Closing a Connection to a Data Source
You should always explicitly close a connection to a data source. That means you
shouldn’t rely on a variable going out of scope to close a connection. Instead, you should
force an explicit disconnect via code. This is accomplished by calling the Close() method
of the connection object.
<Connection Name>.Close()
or
<Connection Name>.Dispose()
Manipulating Data
Understanding DataTables
DataTables contain a snapshot of data in the data source.
You generally start by filling a DataTable, manipulating its results, and finally sending
the changes back to the data source. The DataTable is populated using the Fill() method
of a DataAdapter object, and changes are sent back to the database using the Update()
method of a DataAdapter. Any changes made to the DataTable appear only in the local
copy of the data until you call the Update method. Having a local copy of the data
reduces contention by preventing users from blocking others from reading the data while
it’s being viewed.
If you’re familiar with ADO, you’ll note that this is similar to the Optimistic Batch Client
Cursor in ADO.
Creating a DataAdapter
To populate a DataTable, you must create a DataAdapter. The DataAdapter you’re
going to create will use the connection you’ve already defined to connect to the data
source and then execute a query you’ll provide.
The results of that query will be pushed into a DataTable. As mentioned earlier, there
are multiple connection objects in the .NET Framework.There are multiple ADO.NET
DataAdapter objects as well. You’ll be using the OleDbDataAdapter because you will
be connecting to Microsoft SQL Server.The constructor for a DataAdapter optionally
takes the command to execute when filling a DataTable or DataSet, as well as a
connection specifying the data source (you could have multiple connections open in a
single project).
This constructor has the following syntax:
Dim <Adapter Name> As New OleDb.OleDbDataAdapter ([CommandText],[Connection]);
To add a DataAdapter to your project, follow these steps:
1. Add the following statement immediately below the statement you entered to declare the <Connection
Name> object (in the class header, not in the Load event) to create a variable:
Dim <Data Adapter Name> As OleDb.OleDbDataAdapter
2. Add the following statement at the bottom of the Load event of the form (immediately following the
statement that opens the connection):
<Data Adapter Name> = New OleDb.OleDbDataAdapter(“Select * From <Table Name>”,<Connection Name>)
You must specify the insert, update, and delete statements to use to submit changes from the DataTable to
the data source. ADO.NET lets you customize how updates are submitted by enabling you to manually
specify these statements as database commands or stored procedures. In this case, you‟re going to have
ADO.NET automatically generate these statements for you by creating a CommandBuilder object.
3. Enter this statement in the class header to create the CommandBuilder variable:
Dim <Command Name> As OleDb.OleDbCommandBuilder
The CommandBuilder is an interesting object in that after you initialize it, you no longer work with it directly: It
works behind the scenes to handle the updating, inserting, and deleting of data. To make this work, you have
to attach the CommandBuilder to a DataAdapter. You do so by passing a DataAdapter to the
CommandBuilder. The CommandBuilder then registers for update events on the DataAdapter and provides
the insert, update, and delete commands as needed.
4. Add the following statement to the end of the Form_Load event to initialize the CommandBuilder object:
<Command Name> = New OleDb.OleDbCommandBuilder(<Data Adapter Name> )
Creating and Populating DataTables
1. Create the DataTable variable by adding the following statement on the class header to
create another variable:
Dim <Data set Name> As New DataTable
2. You’re going to use an integer variable to keep track of the user’s current position
(row) within the DataTable. To do this, add the following statement immediately below
the statement you just entered to declare the new DataTable object:
Dim < rowPosition variable Name > As Integer = 0
3. You now have a DataAdapter that allows access to a data source via the
connection.You’ve declared a DataTable that will hold a reference to data. Next add the
following statement to the Load event of the form, after the existing code, to fill the
DataTable with data:
<Data Adapter Name>.Fill(<Dataset Name>)
Search Records.
Dim <Input Variable Name> As String = <Input Filed Name>.Text
Try
If <Input Variable Name> <> "" Then
< Command Name >.CommandText = "SELECT <Filed1,Field2,….> FROM <Table Name>
WHERE <Primary Key Field>=" & CInt(<Input Filed Name>.Text )
< Command Name >. Connection = <Connection Name>
Dim <Data Reader Name> As OleDbDataReader = < Command Name >.ExecuteReader
If <Data Reader Name> .Read = True Then
<TextBox Name>.Text = <Data Reader Name> .Item(<Row Index >).ToString
<TextBox Name>.Text = <Data Reader Name> .Item(<Row Index >).ToString
…….
<Data Reader Name> . Close()
Exit Sub
Else
<Data Reader Name> .Close()
MsgBox("Record not Found: Want to add a Record?")
Exit Sub
End If
End If
Catch ex As Exception
End Try
Dim <Command Name> As New OleDbCommand
Add, Edit, Delete, Update
Records.
Creating New Records
Adding records to a DataTable is performed much like editing records. However, to create a
new row in the DataTable, you must first call the NewRow() method. After creating the new
row, you can set its column values. Follow these steps:
Dim <Datarow Variable Name> As DataRow = <Dataset name>.NewRow()
<Datarow Variable Name> (“<Field Name>”) = <textbox Name>.Text
<Datarow Variable Name> (“<Field Name>”) = <textbox Name>.Text
………
<Dataset name>.Rows.Add(<Datarow Variable Name>)
< Data Adapter Name >.Update(Dataset name)
<rowPosition variable Name>= <Dataset name>.Rows.Count - 1
Editing Records
To edit records in a DataTable, you change the value of a particular column in the desired
DataRow. Remember, though, that changes aren‟t made to the original data source until you
call Update () on the DataAdapter, passing in the DataTable containing the changes. You‟re
now going to add a button that the user can click to update the current record. Follow these
steps:
Double-click the Save button and add the following code to its Click event:
If <Dataset name>.Rows.Count <> 0 Then
<Dataset name>.Rows(<rowPosition variable Name>)(“<Field Name>”) = <textbox
Name>.Text
<Dataset name>.Rows(<rowPosition variable Name>)(“<Field Name>”) = <textbox
Name>.Text
…..
< Data Adapter Name >.Update(Dataset name)
End If
Deleting Records
To delete a record from a DataTable, you call the Delete() method on the DataRow to be
deleted. Follow these steps:
1. Add a new button to your form (not to the group box) and set its properties as shown in
the following table:
2. Double-click the Delete button and add the following code to its Click event:
„ If there is data, delete the current row.
If <dataset Name>.Rows.Count <> 0 Then
<Dataset name>.Rows(<rowPosition variable Name>).Delete()
< Data Adapter Name >.Update(Dataset name)
<rowPosition variable Name>= 0
End If
Data Validation
Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles TextBox1.LostFocus
If TextBox1.Text = "" Or IsNumeric(TextBox1.Text) Then
ErrorProvider1.SetError(TextBox1, "Cant leave blank or cant be
numeric value")
TextBox1.Focus()
End If
End Sub
To check weather the entered text is numeric or not we can use “is numeric”
method to ensure data and validate it.
Error Handling
Try … Catch
VB.NET has a inbuilt class that deals with errors. The Class is called Exception.
When an exception error is found, an Exception object is created. The coding
structure VB.NET uses to deal with such Exceptions is called the Try … Catch
structure.
In the coding area for your button, type the word Try. Then hit the return key on
your keyboard. VB.NET completes the rest of the structure for you:
Try
Catch ex As Exception
End Try
The Try word means "Try to execute this code". The Catch word means "Catch
any errors here". The ex is a variable, and the type of variable it is is an Exception
object.
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As Exception
End Try
When you run your programme, VB will Try to execute any code in the Try part. If everything
goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to
Catch. Add the following to your Catch part:
MsgBox(ex.Message)
Because ex is an object variable, it now has its own Properties and methods. One of these is
the Message property. Run your programme and test it out. Click your button. You should see
the following error message:
The one we didn't handle. But the point about this new message box is that it will not crash
your programme. You have handled the Exception, and displayed an appropriate message for
the user.
If you know the kind of error that a programme might throw, you can get what Type it is from
the Error message box you saw earlier. This one:
Click the View Details links
under Actions to see the
following:
The first line tells us the Type of Exception it is:
System.IO.FileNotFoundException
You can add this directly to the catch part. Previously, you were just catching any error that
might be thrown:
Catch ex As Exception
But if you know a "file not found" error might be thrown, you can add that to the Catch line,
instead of Exception:
Catch ex As System.IO.FileNotFoundException
You can keep the Exception line as well. (You can have as many Catch parts as you want.)
This will Catch any other errors that may occur:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As System.IO.FileNotFoundException
MsgBox(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try … Catch ….Finally:
Try
Catch ex As Exception
Finally
End Try
The Finally part is always executed, whether an error occurs or not. You typically add a Finally
part to perform any cleanup operations that are needed. For example, you may have opened
a file before going into a Try … Catch Statement. If an error occurs, the file will still be open.
Whether an error occurs or not, you still need to close the file. You can do that in the Finally
part.
Crystal Report
How to Creating a Report Using Crystal report in VB.NET?
Using Existing Dataset
1. Open the solution Explorer Window.
2. R.Click on the windows application name.
3. Select add >select “add new Item”.
4. Select Crystal Report from the template list.
5. Select “Add” button.
If the System Popup crystal registration wizard, close that window. Then you will see
crystal report gallery
1
2
3
4
56
7
8
9
10
1. Select “Using the Report Expert” option.Select “OK”.
2. Select “History” from the standard report creation wizard.
3. Click the Browse Button.
4. Select relevant dataset
5. select open button.
6. Select Finish button
7. Select the required table that you wish to add to
the report.
8.Select” Next”.
9.Select the required Fields that you wish to Display
on the report.
10.Select” Next” continuously until get finish button.
11.Select “Finish button”.
12.The Report Design Window Appears
13.At the left side of the report design view, you will
see “field Explorer” window.
14.If you wish, you can use properties window to
change properties of the report..
13
How to Creating a Report Using Crystal report in VB.NET?
Using Database file
1. Open the solution Explorer Window.
2. R.Click on the windows application name.
3. Select add >select “add new Item”.
4. Select Crystal Report from the template list.
5. Select “Add” button.
If the System Popup crystal registration wizard, close that window. Then you will see
crystal report gallery
1
2
3
5
6
4
7
8
9 10
1. Select “Using the Report Expert” option.Select “OK”.
2. Select “Database Files” from the standard report creation wizard.
3. Click the Browse button & Select relevant database
4. select open button.
5. Select the table that want to be insert
6. Click the add button to add the table
7.Select” Next”.
8.Select the required Fields that you wish to Display
on the report.
9.Select” Next” continuously until get finish button.
10.Select “Finish button”.
11.The Report Design Window Appears
12.At the left side of the report design view, you will
see “field Explorer” window.
13.If you wish, you can use properties window to
change properties of the report..
12
Viewing the Crystal Report
How to display the Report (How to view data)
1. Add new windows form in to the Application.
2. Select “Crystal report viewer” tool from the tool box.
3. Draw the suitable surface to display the content..
4. Select the properties window & select the “Report source” item & browse for
the created repot.
5. Select “open”.
6. Select “save”.
7. At the Form load event you will see the data in the Report..
Browse the report that
have been created