0% found this document useful (0 votes)
74 views121 pages

Dot Net

Uploaded by

BALAKUMAR C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views121 pages

Dot Net

Uploaded by

BALAKUMAR C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 121

DACC

Dnyansagar Arts and commerece


college Balewadi pune

BBA(CA) V SEM- 2013


(PATTERN)

DOT NET PROGRAMMING-


(503)
By
Prof Gayatri A Amate
DACC

Unit 1
INTRODUCTION TO .•
NET FRAMEWORK
DACC

.• NET –- WHAT IS IT?•

• Software platform
• Language neutral
• In other words:
.NET is not a language (Runtime and a library for
writing and executing written programs in any
compliant language)
DACC

WHAT IS .• NET

• .Net is a new framework for developing


web-based and windows-based
applications within the Microsoft
• environment.
The framework offers a fundamental shift
in Microsoft strategy: it moves application
development from client-centric to server-
centric.
DACC

.• NET –- WHAT IS IT?•

.NET Application

.NET Framework

Operating System + Hardware


DACC
FRAMEWORK, LANGUAGES,• AND
TOOLS

VB VC++ VC# JScript …

Common Language Specification


isual

ASP.NET: Web Services Windows


and Web Forms Forms
Studio

ADO.NET: Data and XML


ET
Base Class Library
DACC
THE .• NET FRAMEWORK
.NET Framework
Services
• Common Language Runtime
• Windows® Forms
• ASP.NET
– Web Forms
– Web Services
• ADO.NET, evolution of ADO
• Visual Studio.NET
DACC
COMMON LANGUAGE RUNTIME
(CLR)
•CLR works like a virtual machine in executing
all languages.
•All .NET languages must obey the rules and
standards imposed by CLR. Examples:
– Object declaration, creation and use
– Data types,language libraries
– Error and exception handling
– Interactive Development Environment
(IDE)
DACC

COMMON LANGUAGE RUNTIME

• Development
 Common Language Specification (CLS)
– Mixed language applications
Commo•n Type System
(CTS) •
Automatic
 Stand•ard class framework
memory management

– Consistent error handling and safer execution
– Potentially multi-platform
• Deployment
– Removal of registration dependency
– Safety – fewer versioning problems
DACC

COMMON LANGUAGE RUNTIME


Multiple Language Support
• CTS is a rich type system built into the
CLR
– Implements various types (int, double, etc)
– And operations on those types
• CLS is a set of that language
specifications follow
–and
Thislibrary designers
will ensure need between
interoperability
languages to
DACC

COMPILATION IN . NET •

Code in another
Code in VB.NET Code in C#
.NET Language

Appropriate
VB.NET compiler C# compiler
Compiler

IL(Intermediate
Language) code

CLR just-in-time
execution
DACC

INTERMEDIATE LANGUAGE (IL)


• .NET languages are not compiled to machine code. They
are compiled to an Intermediate Language (IL).

• CLR accepts the IL code and recompiles it to machine


code. The recompilation is just-in-time (JIT) meaning it is
done as soon as a function or subroutine is called.

• The JIT code stays in memory for subsequent calls. In


cases where there is not enough memory it is discarded
thus making JIT process interpretive.
DACC
LANGUAGES

• Languages provided by MS
– VB, C++, C#, J#, JScript
• Third-parties are building
– APL, COBOL, Pascal, Eiffel, Haskell, ML,
Oberon, Perl, Python, Scheme, Smalltalk…
ASP.• NET

• Logical Evolution of ASP


– Supports multiple languages
– Improved performance
– Control-based, event-driven execution
– model
– More productive
Cleanly encapsulated functionality
DACC
ADO.• NET
(DATA
AND
• New objects (e.g., DataSets)
XML)
• Separates connected / disconnected issues
• Language neutral data access
• Uses same types as CLR
• Great support for XML
DACC

VISUAL STUDIO.• NET

• Development tool that contains a rich set of


productivity and debugging features
DACC

.NET – HIERARCHY, ANOTHER VIEW •

-
ASP.NET
(Runtime)

CLR
Internet
Manage<! W@b
Informati
applications
on
Services
Runtime Operating system/
i-l ardw
are

CLR

Managed application• Unmanaged •pplicatian•


DACC

NET Tools
Visual Studio .NET is Microsoft's flagship tool for developing

Windows software.

Visual Studio provides an integrated development environment

(IDE) for developers to create standalone Windows

applications, interactive Web sites, Web applications, and Web

services running on any platform that supports .NET.


DACC

.NET TOOL
In addition, there are many .NET Framework tools designed to

help developers create, configure, deploy, manage and

secure .NET applications and components.

Microsoft
• •
isua 10
DACC

SUMMARY

• The .NET Framework


– Dramatically simplifies development and deployment
– Provides robust and secure execution environment
– Supports multiple programming languages
DACC

UNIT 2

Introduction to VB.net
DACC

Operators in
VB.NET
i Arithmetic
operators
J Comparison
operators
i Logical
operators
J Concatenation
operators
DACC

Arithmetic operators
I Arithmetic operators are used to perform arithmetic
I

calculations such as addition and subtraction.

I VB.NET supported arithmetic are listed in the given table.


I
D.ACC

Example:
Operator Purpose Output
Leta=10
+ Addition b=a+5 55
- Subtraction c=a-5 45
* Multiplication d=a*10 500
I Division e=aI6 8.33
Division (integer
\ part only given as f =a\ 6 8
output)

Modulas
MOD (Remainder after g = a mod 7 1
division)
A Power h = aA2 2500
- Assignment m = 100
DACC

Compariso operator
n s
Comparison operators are used to compare two or more

values.

VB.NET supported comparison operators are listed in the

following table.
Example:
Operator Purpose Leta=SO Output

Check if a value is Dim b As


= FALSE
equal to another Boolean
b=(a=55)
Check if a value is
<> b={a<>55) TRUE
not equal to another

Check if a value is
> b=(a>100) FALSE
greater than another

Check if a value is
< b={a<100) TRUE
less than another
Check if a value is
>= greater than or b=(a>=50) TRUE
equal to another

Check if a value is
<= less than or equal b=(a<=75) TRUE
to
another
Check if a string Dim P As string
LIKE matches a given P="Good" FALSE
pattern b=("God" LIKE P)
Check if two object
IS references refer to a
www.ustudy.in
same object.
DACC

. Logical
operators
.
~

LOGICAL
OPERATORS
Operators Description Example Result
OR It will retrieve true value if (25>3) OR (3<5) True
the
operand are true.
AJ.:J It will retrieve true value (25>3) AND (3<5) True
D only
if both operands are true
XOR (25>3) XOR (3<5) False
Both must not be true meaning
only one side should hold true
value
NOT NOT(2=2) False
Reverse true side
DACC

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.
DACC

DATA TYPES AVAILABLE IN VB.• NET

String Decimal

Boolean D ate Time

Integer Data The Object


Data

www.educba.com
DACC

VB.NET Primitive Data Types

IType I Range of Size


Numeric Byte Value
Oto 8 bits
with 255
Short -32768 to 32767 16 bits
no
decimal Integer 32 bits
Long 64 bits
Numeric Single 32 bits
with 64 bits
Double
decimal
Decima 128 bits
l
other True or 16 bits
Boolea False
n Any Unicode char 16 bits

Char
Object-Oriented ApplicationDevelopmentUsing 13
VB.NET
DACC
Control
Flow
In a program, statements may be executed sequentially, selectively or
iteratively.
Every programming language provides constructs to support sequence,
selection or iteration. So there are three types of programming constructs :
 Sequence
 Functions and Procedures

 Selection
 If...Then...Else
statement
 Select Case statement

 Iterative
 For...Next Loop
statement
 Do...Loop statement
DACC

There are mainly 3 types


of loop:
Previous.
code

 For Loop

While Loop rs the c:oind itiorn true7

Yes

 Do Loop l Next code to run


.._................
..............
DACC

Example

Module Modulei

Sub Main()
Dini d As Integer
Ford =0To2
Systeni.Console.WriteLine("In the For Loop")
Nextd
End Sub

End Module
DACC

IFO ]L(O)
R (O)JP)
• The For loop is the most popular
loop.
• For loops enable us to execute a series
ofexpressions
multiple numbers of times.
·Syntax
;
For indexvstart to end[Step step]
[statements]
[Exit For]
[statements]
Next[index]
DACC

WJlm }L(O)
llice (O)JP
•While loop keeps executing until the
condition against which it tests remain true.

·Syntax
;
While condition
[statements]
End While
DACC
Module Modulei

Sub Main()
Dim d, e Integer
As
d=o
e =6
While e >4
e -= 1
d+=l
End While
System.Console.WriteLine("The Loop ran " & e
"times") &
End Sub

End Module
DACC

•The Do loop keeps executing it's statements while or until the


condition is true.
•Two keywords, while and until can be used with the do loop.
•The Do loop also supports an Exit Do statementwhich makes
the loop to exit at anymoment.

·Syntax;
Do[{while I Until}
condition] [statements]
[Exit Do]
[statements]
Loop
oAcc Example
;
~ Module Modulei

Sub Main()
Dim str As String
Do Until str = "Cool"
System.Console.WriteLine("What to do?")
str = System.Console.ReadLine()
Loop
End Sub

End Module
DACC
WI. NDOWSFORMS

VB.Net programmers have made extensive use of forms to


build user interfaces.
Each time you create a Windows application, Visual Studio
will display a default blank form, onto which you can drag
and drop controls from the Visual Studio Toolbox window
Toolbox • If X Form}. [GJesi'gn]*
r> All Windows > X
Forms
... Common Controls g5) Form!
~ Pointer
(ill Button

~ CheckBo
x
I stBo
Checkedlix
m .
Com ho ox
~ B
'ii Date Tinn eP i
A cker

A Label

~. LinkLab-
el
-
2e::
: ListBox
!!::!

!!;] ListView

Maskedrrext:B
m ox
m MonthCalenda
~ r
ITT' Notifyicon
CREATE NEW FORM IN VB. NET •

Step 1. aa Microsoft Visual


Studio
File Edit View Debug Team Data Too.ls Test Window
e; New Ctrl+N
Project ...
::] New Web Site ... Shift+Alt+N
.. ~I .... T·-·-· n ••. : •• .a.

~-

Step 2 : Select project type from New project dialog Box.

New Project
Recent Templates
~[ .N_ET_F _re_wa_m._·or_k_4~~] Sort
Installed Templates by: [ Defa11Jlt

WPF Applicati on


Office Console
Cloud Application
When you add a Windows Form to your project, many of the forms properties are set by
default. Although these values are convenient, they will not always suit your
programming needs. The following picture shows how is the default Form look like.

oolbox • ~ X Forml.vb [Design] X


All Windows Forms

r
""
~ Common
ControlsPointer
~
§) Button
~ CheckBox
~. CheckedlistBox -
~ ComboBox
ii DateTimePicke
A r
A
~
Label
Linklabel L
:!:!~ ListBox
~!::
! ListView
~ MaskedT
r extBox
& MonthCalendar
Notifykon
1
~ NumericUpDo.
..
II)
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 −
Properties • X
Forml System.Windows.Forms.Form
f1.

~~' [Q] f
El Accessibility
AccessibleDescription
AccessibleName
AccessibleRole Default
El Appearance BackColor
Backgroundlmage
D Control
(none)
Backgroundlmagelayout
Cursor D
Tile
1±1 Font Default
ForeColor Microsoft Sans Serif, 8.25pt
FormBorderStyle • ControlT ext
RightT cleft Sizable
RightT oleftlayout No
False
Forml

Text
The text associated with the control.
VISUAL STUDIO IDE
MyFirstApp - Microsoft Visual Studio ~ 0 :,? Quick Launch (Ctr!+ Q) p c5l
(Administrator)
Edi View Pro·ect Buil Debu Team Format Tools Test Ana e Window Hel Menu bar x
t d Signin
B


Debug ·-A-ny·C·P·U---·-~-st.art_·_P•_T; ool bar
Toolbox • !/, Forml.vb [Design] -ll X _o_b.._!e_ct_B_r_ows_e_r • .. Solution Explorer
X
Search Toolbox G'l '0·~Gsi1r@
.,, All Windows
P• Search Solution Explorer (Ctr!+;)
•~· Forml
Forms .... P•
~ Pointer
1£ BackgroundWorker ~ Solution 'MyFirstApp' (1
' BindingNavigator project)
.,, I!!! MyFirstApp
Q0 BindingSource
~ MyProject

vb.net form
ij1 Button
I> •·• References
li CheckBox ) I> 19 Forml.vb
D CheckedlistBox
Ii] ColorDialog
g: ComboBox solutions
:
exolorer
ContextMenuStrip
[;,~ DataGridView

I
~ DataSet
0 DateTimePicker
Ii,!

y
DirectoryEntry
jii DirectorySearcher
~ DomainUpDown
ErrorProvider
Eventlog
FileSystemWatcher
FlowlayoutPanel
Toolbox
Ii] FolderBrowserDial.
..
~
FontDialog
('.]
GroupBox
i;
HelpProvider
1 ..,.
----------------------------------------------------------
a1 HScrollBar .
a 1' Publish •
- -
Visual Basic.NET IDE is built out of a collection of different windows. Some
windows are used for writing code, some for designing interfaces, and others
for getting a general overview of files or classes in your application.
I> All Windows
Forms
eunw• ...
,l] ·-·
It Pointer
.,
w) Button
0
a-
CheckBox
a-
a-
CheckedlistBox
~ ComboBox
~
DateTimePicker
A Label

.A ListVie
Linklabel

.. ..w
~ - ListBox

(.). MaskedT
extBox
~
MonthCalendar
6: Notifykon
[IE
NumericUpDown
="A
~ PictureBox
El ProgressBar
0 RadioButton
·
QI:
TreeVie
RichT
w extBox
-
§] TextBox
ta ToolTip
Label Control
Microsoft Visual Studio .NET controls are the graphical tools you use to build the
user interface of a VB.Net program. Labels are one of the most frequently used
Visual Basic control.
A Label control lets you place descriptive text , where the text does not need to be
changed by the user. The Label class is defined in the System.Windows.Forms
namespace.
~~~~~~~~~~~~~~~-

~ [J(g]L8
Form1
]
I This is my first Lable I
eu,ld Otbuv Toob
Oobug • """"
T.-,.t ~·


b;t.m,oru

~ ...... ,.
Window tfflp

'

p
T~-- ~---.=.1¥·¥111
== n A

)( p J/ -Public Clus C le- di +• ~...c.h::,,oh..ot.Ol~(C.I• P·


:;) 2_..J
Cclla~AI Soluuoo'Oud<Soluuoo"(
it RKendyUs.ed
0(Loul
Public Sh•rff S... ,..in()
Di• now • ~tCwnflt~t•()
( n .ole.WriteUM(afoday's d.ate b (t}. ", now)
"

-
C!!Quk110..t.


J, MyP,-,
•• lttf fn«,S
"--111!111
C!)O.,.,ul<•A"°'Y"" lnd Sub
we .
i'
.
(.......,
,.
'" 0 ~o-1:Ttii


i .. . . .
SIO(tgt,A«OUl\t1
. 1 t ™'°td Func-Uon Gct(UM"Cn.t0ai~()
Rttt,,,rn
Et.:!
.Hcw.O..tc
As 0.t•


.,. My.,_.
'. $°Af«encH

. .OtfM
..
b t M " J 11 Junct1M
(nd ClHt y') p,K\19H-conf,g

"
• • (mut.10, ,0,.s ~ • ~ Undlffl1.vb

..

Con.nm 01 IN

M ..... (c,,MKUOnt •

"

-. ....... ,... ...


h,gt, ....... t Fows on)'Ol.lf

o ~~ '
HoltN s.v ic•P
C~ (",.,tJ:..1~,Dl:frN@

:-
Too,bo, r C Mdtn

&rorl1t1

0 ~ t Add to Sourc• (or,trol ...


-. .......
;1 Q\ldSo'ut,on
,... ...
~1

h
On 11111-. """"I tlm
$01t,,,w•
eeee,w., s.,mpWy the ftit.
C~
Windows Forms
VB.Net programmers have made extensive use of forms to build user
interfaces. Each time you create a Windows application, Visual
Studio will display a default blank form, onto which you can drag and
drop controls from the Visual Studio Toolbox window.

Toolbox • X Forml. X
> AllWindows fl. ;.. [DesignJ*
Forms
aSJForml
• Common
~ Pointer
Controls
_J
~ Button
~ CheckBox
~' CheckedlistBo
~ Combox
'ii DateTimBox
ePicke
A Label
r
A Linklabe
~ l
::!::!!:
!~
ListBox -
[!;] ListView
MaskedTextBo
fil x
MonthCalendar
~
[Pl Notifylcon
NumPrid Jnnn ...
• The first step is to start a new project and build a form.

• Open your Visual Studio and select File->New Project and select
Visual Basic from the New project dialog box and select Windows
Forms Application.

• Enter your project name instead of WindowsApplication1 in the


bottom of dialogue box and click OK button.

• The following picture shows how to crate a new Form in Visual Studio.

File Edit View Debug Team Data Tools: Tes.t Window


~ New Project ... Ctrl-e N
• New Web Site ... Shift+Alt+N
~ "- I -· , • "T" - - - n - - ; - _.._
Select project type from New project dialog
Box New Project

Recent Templates: , .NET Firameworlk 4 ...,... I Sort

by: I Def au l't


ImstaHedlTem p'la1:es
Windo1Ns Forms Application

WPF Application

:-,,
Office Com sol e Appl i cati on
Cl o-ud

When you add a Windows Form to your project, many of the forms properties
are set by default. Although these values are convenient, they will not always
suit your programming needs. The following picture shows how is the default
Form look iill!II!
like.

III········=·~·
I> All VtJindc,,vvs Forms [Design] :X::
~ Connmon Controls: ~
...!;J Form1
~ Pointe.-
j~J Bult:t:o,n


~ CheckB-ox
l§= Ch e-cked Lis:tBox
-
tl
~ - Comb-oBox

1DII D-aiteTinnePic!;.:e,,-
FormCL.vb
A Label
.A. LinkLab>el

-
~ - Li..tBo·><
Li ..tVi evv
--
1\11 a s:lkedfT ext:B ox
1\11 onthCal end arr

~ -- IN oti,fylcon
IN UJ nn er~cU pDo ...
UNIT 3:
Object Oriented
Programming in
vb.net
CLASS AND OBJECT

When you define a class, you define a blueprint for a


data type. This doesn't actually define any data, but it
does define what the class name means, that is, what
an object of the class will consist of and what
operations can be performed on such an object.

Objects are instances of a class. The methods and


variables that constitute a class are called members of
the class
OBJECT-ORIENTED (OO) PROGRAM

• Objects
- Consist of one
or more data
values which
define the state
or properties
of the object
- Encapsulated
by (methods) that can be applied to that
a set of functions
object
CONSTRUCTORS AND DESTRUCTORS
• Examine first line of code for a form in the Editor

A class constructor is a special member Sub of a class that is


executed whenever we create new objects of that class. A
constructor has the name New and it does not have any return type.
Following program explains the concept of constructor −
DACC

 Class Line
 Private length As Double ' Length of a line
 Public Sub New() 'constructor
 Console.WriteLine("Object is being created")
 End Sub

 Public Sub setLength(ByVal len As Double)
 length = len
 End Sub

 Public Function getLength() As Double
 Return length
 End Function
 Shared Sub Main()
 Dim line As Line = New Line()
 'set line length
 line.setLength(6.0)
 Console.WriteLine("Length of line : {0}", line.getLength())
 Console.ReadKey()
 End Sub
 End Class
DACC

 When the above code is compiled and


executed, it produces the following result −

 Objectis being created


 Length of line : 6
DACC

 A default constructor does not have any


parameter, but if you need, a constructor can
have parameters. Such constructors are called
parameterized constructors. This technique
helps you to assign initial value to an object at
the time of its creation as shown in the
following example −
DACC

 Class Line
 Private length As Double ' Length of a line
 Public Sub New(ByVal len As Double) 'parameterised constructor
 Console.WriteLine("Object is being created, length = {0}", len)
 length = len
 End Sub
 Public Sub setLength(ByVal len As Double)
 length = len
 End Sub

 Public Function getLength() As Double
 Return length
 End Function
 Shared Sub Main()
 Dim line As Line = New Line(10.0)
 Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
 'set line length
 line.setLength(6.0)
 Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
 Console.ReadKey()
 End Sub
 End Class
DACC

 When the above code is compiled and


executed, it produces the following result −

 Objectis being created, length = 10


 Length of line set by constructor : 10

 Length of line set by setLength : 6


DACC

DESTRUCTOR
 A destructor is a special member Sub of a class that is
executed whenever an object of its class goes out of scope.

 A destructor has the name Finalize and it can neither return a


value nor can it take any parameters. Destructor can be very
useful for releasing resources before coming out of the
program like closing files, releasing memories, etc.

 Destructors cannot be inherited or overloaded.

 Following example explains the concept of destructor −


DACC

 Live Demo
 Class Line
 Private length As Double ' Length of a line
 Public Sub New() 'parameterised constructor
 Console.WriteLine("Object is being created")
 End Sub

 Protected Overrides Sub Finalize() ' destructor
 Console.WriteLine("Object is being deleted")
 End Sub

 Public Sub setLength(ByVal len As Double)
 length = len
 End Sub

 Public Function getLength() As Double
 Return length
 End Function

 Shared Sub Main()
 Dim line As Line = New Line()
 'set line length
 line.setLength(6.0)
 Console.WriteLine("Length of line : {0}", line.getLength())
 Console.ReadKey()
 End Sub
 End Class
DACC

 When the above code is compiled and


executed, it produces the followin result −
g
 Object is being created
 Length of line : 6

 Object is being deleted


DACC

METHOD OVERLOADING

visual basic, Method Overloading means defining multiple
methods with the same name but with different parameters. By
using Method Overloading, we can perform different tasks
with

the same method name by passing different parameters.

Suppose, if we want to overload a method in visual basic, we need
to define another method with the same name but with different
signatures. In visual basic, the Method Overloading is also called
 as compile time polymorphism or early binding.

Following is the code snippet of implementing a method
overloading in a visual basic progra
DACC

 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.
DACC

 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.

 Catch − A program catches an exception with an exception handler at


the place in a program where you want to handle the problem. The
Catch keyword indicates the catching of an exception.

 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.
DACC

 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 −
DACC

 Try
 [ tryStatements ]
 [ Exit Try ]
 [ Catch [ exception [ As type ] ] [ When expression ]
 [ catchStatements ]
 [ Exit Try ] ]
 [ Catch ... ]
 [ Finally
 [ finallyStatements ] ]
 End Try
DACC

EXCEPTION CLASSES IN .• NET FRAMEWORK


 In the .Net Framework, exceptions are represented by classes. The
exception classes in .Net Framework are mainly directly or indirectly
derived from the System.Exception class. Some of the exception
classes derived from the System.Exception class are the
System.ApplicationException and System.SystemException classes.
 The System.ApplicationException class supports exceptions
generated by application programs. So the exceptions defined by the
programmers should derive from this class.
 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 −
DACC

Exception Class Description


System.IO.IOExcept Handles I/O errors.
i on
System.IndexOutOf Handles errors generated when a
RangeException method refers to an array index out
of range.
System.ArrayTypeM Handles errors generated when
i type is mismatched with the array
smatchException type.
System.NullReferen Handles errors generated from
ceException deferencing a null object.
System.DivideByZer Handles errors generated from
oException dividing a dividend with zero.
System.InvalidCast Handles errors generated during
Exception typecasting.
System.OutOfMem Handles errors generated from
oryException insufficient free memory.
System.StackOverfl Handles errors generated from
owException stack overflow.
DACC

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 Finally keywords.
Following is an example of throwing an exception
when dividing by zero condition occurs −
DACC

 Live Demo
 Module exceptionProg
 Sub division(ByVal num1 As Integer, ByVal num2 As
 Integer) Dim result As Integer
 Try
 result = num1 \ num2
 Catch e As DivideByZeroException
 Console.WriteLine("Exception caught: {0}",
 e) Finally
 Console.WriteLine("Result: {0}", result)
 End Try
 End Sub
 Sub Main()
 division(25, 0)
 Console.ReadKey()
 End
 Sub
End Module
DACC

 Exception caught:
System.DivideByZeroException Attempted to
:
divide by zero.
 at ...

 Result: 0
DACC

 CreatingUser-Defined Exceptions
 You can also define your own exception. User-
defined exception classes are derived from the
ApplicationException class. The following
example demonstrates this −
DACC

 Live Demo
 Module exceptionProg
 Public Class TempIsZeroException : Inherits ApplicationException
 Public Sub New(ByVal message As String)
 MyBase.New(message)
 End Sub
 End Class
 Public Class Temperature
 Dim temperature As Integer = 0
 Sub showTemp()
 If (temperature = 0) Then
 Throw (New TempIsZeroException("Zero Temperature
 found")) Else
 Console.WriteLine("Temperature: {0}", temperature)
 End If
 End Sub
 End Class
 Sub Main()
 Dim temp As Temperature = New
 Temperature() Try
 temp.showTemp()
 Catch e As TempIsZeroException
 Console.WriteLine("TempIsZeroException: {0}",
 e.Message) End Try
 Console.ReadKey()
 End Sub
 End
Module
DACC

 When the above code is compiled and


executed, it produces the following result −

 TempIsZeroException: Zero Temperature found


DACC

 Throwing Objects
 You can throw an object if it is either directly or indirectly derived from the System.Exception class.

 You can use a throw statement in the catch block to throw the present object as −

 Throw [ expression ]
 The following program demonstrates this −

 Module exceptionProg
 Sub Main()
 Try
 Throw
 New
 Applicati
 onExcept
 ion("A
 custom
 exception

_ is being

thrown
here...")
Catch e
As
Exceptio
n
Console.WriteLine(e.Message)
Final
DACC

UNIT :• 5

 Architecture Of
ADO.Net
DACC

 ADO.NET provides a bridge between the front


end controls and the back end database. The
ADO.NET objects encapsulate all the data
access operations and the controls interact
with these objects to display data, thus hiding
the details of movement of data.
DACC

DaitaiP rovi de r 0'61taSet

Connection Dat3Ad apt,e r Data Re lati n nGDJl-


ectiDn

Ii Select
Comman-d DataTab le Col le rtlon
cornrnenc
Ii Insert:
D.=£a1iabJ
commend eD
I
=ita rows

Delete DataGDlum
ns
command
Dcata
Iii IJjJ'd.ate
co n:strai
command nts

D.ata re
Sto
DACC

THE DATASET CLASS

 The DataSet Class


 The dataset represents a subset of the database.
It does not have a continuous connection to the
database. To update the database a reconnection
is required. The DataSet contains DataTable
objects and DataRelation objects. The
DataRelation objects represent the relationship
between two tables.
 Following table shows some important properties
of the DataSet class:
DACC

Properties Description
CaseSensitive Indicates whether string comparisons within the data tables are case-
sensitive.
Container Gets the container for the component.
DataSetName Gets or sets the name of the current data set.

DefaultViewManager Returns a view of data in the data set.

DesignMode Indicates whether the component is currently in design mode.

EnforceConstraints Indicates whether constraint rules are followed when attempting any
update operation.
Events Gets the list of event handlers that are attached to this component.

ExtendedProperties Gets the collection of customized user information associated with the
DataSet.
HasErrors Indicates if there are any errors.
IsInitialized Indicates whether the DataSet is initialized.

Locale Gets or sets the locale information used to compare strings within the
table.
Namespace Gets or sets the namespace of the DataSet.

Prefix Gets or sets an XML prefix that aliases the namespace of the DataSet.

Relations Returns the collection of DataRelation objects.

Tables Returns the collection of DataTable objects.


DACC

THE DATATABLE CLASS

The DataTable class represents the tables in the database. It has the following important properties; most of
these
properties are read only properties except the PrimaryKey property:
The following table shows some important methods of the DataTable class:

Properties Description
ChildRelation Returns the collection of child
s relationship.
Columns Returns the Columns collection.
Constraints Returns the Constraints collection.
DataSet Returns the parent DataSet.
DefaultView Returns a view of the table.
ParentRelatio Returns the ParentRelations collection.
ns
PrimaryKey Gets or sets an array of columns as the
primary key for the table.
Rows Returns the Rows collection.
DACC

Methods Description
AcceptChanges Commits all changes since the last
AcceptChanges.
Clear Clears all data from the table.
GetChanges Returns a copy of the DataTable with
all changes made since the
AcceptChanges method was called.
GetErrors Returns an array of rows with errors.
ImportRows Copies a new row into the table.
LoadDataRow Finds and updates a specific row, or
creates a new one, if not found any.
Merge Merges the table with another
DataTable.
NewRow Creates a new DataRow.
RejectChanges Rolls back all changes made since the
last call to AcceptChanges.
Reset Resets the table to its original state.
Select Returns an array of DataRow objects.
DACC

THE DATAROW CLASS

 The DataRow object represents a row in a


table. It has the following important properties:
Properties Description
HasErrors Indicates if there are any errors.
Items Gets or sets the data stored in a
specific column.
ItemArrays Gets or sets all the values for the row.
Table Returns the parent table.
DACC

The following table shows some important


methods of the DataRow class:
Methods Description

AcceptChanges Accepts all changes made since this method


was called.

BeginEdit Begins edit operation.

CancelEdit Cancels edit operation.

Delete Deletes the DataRow.

EndEdit Ends the edit operation.

GetChildRows Gets the child rows of this row.

GetParentRow Gets the parent row.

GetParentRows Gets parent rows of DataRow object.

RejectChanges Rolls back all changes made since the last


call to AcceptChanges.
DACC

 The DataAdapter Object


 The DataAdapter object
acts as a mediator
between

the DataSet object and
the database. This helps
 The DataReader object is an alternative to the
the
DataSet and DataAdapter combination. This object
Dataset
provides atoconnection
contain data
oriented access to the data
from
recordsmultiple databases These objects are suitable
in the database.
or
for read-only access, such as populating a list and
other data source.
then breaking the connection.
The DataReader Object
DACC

DBCOMMAND AND DBCONNECTION OBJECTS

 The DbConnection object represents a


connection to the data source. The connection
could be shared among different command
objects.

 The DbCommand object represents the


command or a stored procedure sent to the
database from retrieving or manipulating data.
DACC

 What is DataBinding?
 DataBinding is a powerful feature provided by the .NET
Framework that enables visual elements in a client to connect
to a datasource such as DataSets, DataViews, Arrays, etc. Some
of the visual elements in the client can be TextBox, Datagrid,
etc. A two-way connection is established such that any changes
made to the datasource are reflected immediately in the visual
element and vice versa.
 Below is a graphical description of the concept of databinding:

DACC

Data
Grld
Datasource1

Comp Bln~it .g
lax Da~a

Tex1
1m: Ellndl ng ODJect ··.·=.-ii
ODJect
Datasowree1
OK
DACC

 DataBinding before .NET



In the earlier databinding models, the
datasource that could be used was usually
limited to a database. All DBMS systems
provided their own APIs to help in building GUI
applications and quickly bind them to the data.
Programmer did not have the flexibility to
control the databinding process with the result
that most developers avoided the use of
databinding.
DACC

 DataBinding with .NET


 The .NET Framework provides a very flexible and
powerful approach to databinding and allows the
programmer to have a fine control over the steps
involved in the whole process. One of the biggest
improvements with .NET has been the introduction
of databinding to web pages through the use of
.NET server-side web controls. Hence, building
data driven web applications has been greatly
simplified. Please note that this article only deals
with data binding in .NET Windows Forms.
DACC

ADVANTAGES OF DATABINDING

 Databinding in .NET can be used to write data driven


applications quickly. .NET data binding allows you to write less
code with fast execution but still get the work done in the best

way.
.NET automatically writes a lot of databinding code for you in
the background (you can see it in "Windows Generated Code"
section), so the developer does not have to spend time writing
code for basic databinding, but still has the flexibility of
modifying any code that he would like to. We get the benefits

of bound as well as unbound approach.
Control over the Databinding process by using events. This is
discussed in more detail later in the article.
DACC

DISADVANTAGES OF DATABINDING

 More optimized code can be written by using


the unbound or traditional methods.
 Complete flexibility can only be achieved by
using the unbound approach.
DACC

DATAFLOW DURING DATABINDING


Control

Datil Bound Properly Dc1tci Bound


Data Boond Properly
II I I Prope1ty I
l

I I
, r ,r
1 '
Binding Object Binding Object
Binding Objeot
II I I I
j • DataBindin s (l •llectioo a
~ I
BlndlngCor tex Object
1 ' ,r
,
'
Curremc.ytvlanagsr Object Ourrsnq,Managsr Objsct PmpsrtyManager Object

Property
[lamaSourc
e1
DamaSourca2
9
M~Qtifa
I cl I
DACC

UNIT 5 :• CRYSTAL REPORT


DACC

CRYSTAL REPORT
 Crystal Report that enables you to generate reports to show
your data retrieved from a database
 how to get data stored in a table of a Microsoft SQL SERVER
database to display on a form of your project.

 Suppose that you want to create a report to display the data


from TblProduct of SaleAndStock database. This database
exists in Microsoft SQL SERVER(in my machine, i have SQL
SEVER 2005). The user that has a right to login to the database
is called sa and its password is 123. This login information is
useful when we connect the database using VB.NET code. The
steps below will help you to get thing done.
DACC

STEP 1: ADD A DATASET TO THE PROJECT •

Now create a new project in Visual Studio 2008.


In my case, i created a project called ReportVB.
Right-click the project name->Add->New Item.
Under Categories, select Data and under
Templates select Dataset.
Add New Item - RcportVB 1-'ri'I~

,-C-•t_•~g_o_,;_._"--------Ter-rtpt-ete-sa --,
Common Items Visual Studio installed templates
Code !~Dataset! b£ UNQ to SQL Classes
Data tj Local Database local Database Cache:

I
!:nbe:ral CJ Service-based Database: ~XML f;I•
Windows Forms ~ XML Schema ,;Ji' XSLT File
Reporting My Templates
Workflow ~ Search Online: Templates ...
WPF

A DataSe:t for using data in your application

Name:: DataSet.2.xsd

~--A d dJ( ~l ~--A d dJ( ~l c_a_n_c_•_I


I
c_a_n_c_•_I_~
DACC

 On the Server Explorer next to the active


dataset window, click Connect to Database icon
to add a connection to the database server. On
the Add Connection dialog, click Change button
of the Data source block to show the Change
Data Source dialog
DACC

Add Connection

Enter information to connect to the selected data source or click Change" to


"
choose a different data source and/or provider,

Data source:
Microsoft ODBC Data Source (ODBC) Change ...
Microsoft ODBC Data Source (ODBC)
Data source specification

@ Use user or system data source name:

..... Refresh

e) Use connection string:

Build...

l.oqin
information

User name:

Password:

Advanced ...

Test Connection ~~~O_K~~~


Test Connection

I
~~~O_K~~~I
[~~c_a_n_c_.e_l~~

[~~c_a_n_c_.e_l
DACC

 Then on the Change Data Source dialog, select


Microsoft SQL Server. After that you will see a new
Add Connection dialog that shows the Server
name box. In this box, you need to enter the name of
your SQL SERVER. In my case, this name is Dcc-
pc.

 +In the Log on to the server block, select Use SQL


Server Authentication. Then type the user name
and password in to the User name box and
Password box.
DACC

 In the Connection to a database, select Select


or enter a database name option. Then click
the dropdown list to select SaleAndStock
database( a sample database used in this
tutorial).
Add Connection

Enter Change" to
information
to connect to
the selected
data source or
click "
Microsoft SQL Server (Sql(lient) Change ...
choose a
differert data
source and/or
provider. R_ef_res_h
R_ef_res_h_. .J

Data source:
Microsoft SQL Server (Sql(lient)

Server name:
Dec-pc "" ....._[_

Log on to the server

I Use Windows Authentication


ro, Use SQL Se-ver Authentication

User name: sa

Password: •••

[] Save my password

Connect to a database

ro Select or erter a database name:

_1t dbstuden:
- master Ad
Advanced ...
model
msdb
SaleAndStock c_a_n c _e_,
Sales
School Mc nagement
temp db
DACC

 Click Test Connection button to test the


connection to the SQL SERVER. If there is a
dialog showing that the Connection is succeed,
it means that you can move to the next step. If
an error occurs you need to check what you
have provided again.
DACC

 Step 2: Add the TblProduct table to the dataset

 After you connected successfully to the SQL


Server database, look Server Explorer again
and click Data Connection to expand it then
select the connection that you have created in
the previous step. Then click Tables to expand
and drag the TblProduct table to the dataset
designer window.
DACC

I
Server Explorer DataSetl.xsdl Forml.vb [Desi n] '"' x
rt'.JJl~H
dJ Data Connections G
El tl
dcc-
Database
!fl
pc.SaleAndStock.dbo
El Diagrams
llllll
$ Iii Ii!]
1±1 PasteCopy Of TblContact
l
Errors

1 IIfl Switchboard Items
± Im TblBoo
1±1
1 IIfl TblBook
! IIfl -
fl
$ IIfl TblContact
TblCategory
1±1 Iii ~ TblCustomer
!
TblEmployee
fl Ii!:!
$· IIfl TblFortuneData
1 tblfo.rtuneTellerData
Iii Tbllncome
1±1

±
1 Im Tbllab
1 IIfl Tbllogln
$
± Im
El IIfl TblProduct
1 TblMonthlyEarning
rr] Product!D Product!D
m
rr] ProductName ProductNam
e
Quantity
rr] Quantity
UnitPrice
1 IIfl UnitPrice
rr] Category!
± TblProductlD
Category!D
1
$· IIfl
1±1··· ~ TblPublisher Fill,GetData
TblRoomStudent
$ bi) TblRoom O
1±1 IIfl TblSaleMaster
r±i. ~ Thk,-
Im TblSaleDetail G
~ I 1±1 nrF>m
.. I
l
DACC

 Step 3: Add a Crystal Report and link to the


table of dataset

 Now you have a schema of a dataset that


connects to the TblProduct of the SaleAndStock
database located in SQL Server. The next step
is to add a Crystal Report item in to your
project.
DACC

 Right-click the project name(ReportVB)->Add-


>New Item. On the New Item dialog, under
Categories select Reporting and under
Templates select. You will see the Crystal
Reports Gallery dialog. Select As a Blank
Report to create a blank report and accept the
default name(CrystalReport1).
DACC

,
. Add New Item - ReportVB
·
Cateqories Tem p,1 ates:
.-----------------,
• Common Items .6 Vis11.Jall Studio installed templates
-
Code I Report
Crysta
Data ~ Report
Gen em I .F."I
- Report \N'i!Zard
Web ~
Windows Forms My Templates-----------------
[ Rep o,rti n g ] - 4lJ Sea rich On Ii n e Tenn pl ates ...
\IVorkflow

A Crystal Report file that publishes data to a Windows or Web form

Nanne: Crysta I Rep oli:2. rpt


I

Add -1 ......_[ _ c_an_c e_, l


L
,
 Tolink to the table of the dataset, right-click
Field Explorer next to the active window of
CrystalReport1 then select Database Expert.
You will see the dialog as shown below:
Browse the daU source for the tables you want to add.
(Note: to edit the alias for a table, select the table in the 'Selected Tables' tree and click on it or
push
the F2 key)
Available Data Sources: Selected Tables:
8 e DataS.U
$ eJADO.NET DataSets
Iii] TblProduct
8 ~ ReportVB.DataS.U
~ TblProduct
IE 0.NET Objects
E:)Current »
Connections
E:)Favorite:s
0History
~ Create
New Connection

OK 11 Cancel
DACC

CRYST

 Select Project Data and select ADO.NET DataSets,


then you will see the TblProduct table. Select this
table and click the arrow button to add the table to
the Selected Table area. Click OK.

 +Now back to the active window of the


CrystalReport1 and drag fields of TblProduct table
that you want to the designer area of the
CrystalReport1.
DACC

Field CrysltalReporU.rpt' DataSetl.xs Forml.vb [Des n]


Explorer
El·· Database " d i
Fields;
ti El-·~ ThlPro,duct
I·•• 1 • • • • • 1 • • • • 1 • • • • 1 • • ·4· • • 1 • • • • 1 •
·1 ·2· ·3· ·5·
i···-~ ProductlD ,.. Section 1 (Report Header )

i···-~
ProductName
i···-~ Quantity ,.. Section2 (Page Header )
i···-~
L...~ UnitPrice
CategoryID
i -·~ Formula Fields Prodl!lctlD Pro dl!l,ct Name Q l!lantity :unitPrice, CateqorylD
,.. Sedion3 (Details )
j---· m Parameter
Fields
frodUJctlD : Q UJantiti :unitPrice: s;ategorylD
i···· ~ Group Name
Fields
,.. Sedion4 (Report Footer )
i····~ Running
Total Fields
iiJ.. ]: Special
,.. Section5 (Page Footer )

I
Fields .
III··= Unbound Fields
DACC

 Step 4: Add a Crystal Report Viewer control to


the form of the project( look for this control in
the Toolbox) and writing VB.NET code on the
form load event.

 +Accept the default name of the Crystal Report


Viewer(CrystalReportVewer1)
DACC

 Open the code window by double-click the form and in the Form1_load procedure write the following code:

 Dim rpt As New CrystalReport1() 'The report you created.


 Dim myCon As SqlConnection
 Dim myAdapter As SqlDataAdapter
 Dim myDataset As New DataSet1() 'The DataSet you created.
 myCon = New SqlConnection("Server=(local);Database=SaleAndStock;User=sa; Password=123;")

 myAdapter = New SqlDataAdapter("Select * FROM TblProduct",


 myCon)
 myAdapter.Fill(myDataset, "TblProduct")
 rpt.SetDataSource(myDataset)
CrystalReportViewer1.ReportSource = rpt
 You also need to add the line of code below to the general declaration section of form module:

 Imports System.Data.SqlClient

 Therefore, the full code becomes as shown below:

 Imports System.Data.SqlClient
 Public Class Form1

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


 MyBase.Load
 Dim rpt As New CrystalReport1() 'The report you created.
 Dim myCon As SqlConnection
 Dim myAdapter As SqlDataAdapter
 Dim myDataset As New DataSet1() 'The DataSet you created.
myCon = New SqlConnection("Server=(local);Database=SaleAndStock;User=sa; Password=123;")
 myAdapter = New SqlDataAdapter("Select * FROM TblProduct",
 myCon)
 myAdapter.Fill(myDataset, "TblProduct")
 rpt.SetDataSource(myDataset)
CrystalReportViewer1.ReportSource = rpt
 End Sub
 End Class
 +Run your project and see the result.
DACC

 Now the designing part is over and the next


step is to call the created Crystal Reports in
VB.NET through Crystal Reports Viewer .
control
 Select the default form (Form1.vb) you created
in VB.NET and drag a button and
CrystalReportViewer control to your form.
DACC

----=-~--~----~--~~~~----~-~~---~-~-~-·~-~~-------..... .
~Form1 ~~~ .
.
Show Report

lZoom factor: 100'%


DACC

 Select Form's source code view and put the


code on top.

 Imports CrystalDecisions.CrystalReports.Engine

 Put the following source code in the button


click event
DACC

 Imports CrystalDecisions.CrystalReports.Engine
 Public Class Form1
 Private Sub Button1_Click(ByVal sender As System.Object,
 ByVal e As System.EventArgs) Handles Button1.Click
 Dim cryRpt As New ReportDocument
 cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt")
 CrystalReportViewer1.ReportSource = cryRpt
 CrystalReportViewer1.Refresh()
 End Sub
 End Class
DACC

 NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH
HERE\CrystalReport1.rpt")

The Crystal Reports is in your project location, there you


can see CrystalReport1.rpt . So give the full path name
of report here.
After you run the source code you will get the report like
this.
DACC

- ....-- ---------------------------------- -------------------------------- - - -

~ Form ~LQ]
1
~

Product Product Product pnce


name
10.00
1 Product1
15.00
2 Product2 350.00
3 Product3 75.00
4 Product4 100.00
5 Product5
.::·:"· .
:.:::::::· ...............
. ............ . ...
·:::::=:::· :: ............
.
j'Zoom
Cu Facto : r 100'%
DACC
DACC
DACC

You might also like