87
www.sfkinfotech.com Sarfaraz Khan - 9763987372 Introduction to Visual Studio .NET: Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It can be used to develop console applications, Windows applications, Web applications, Mobile Applications, Windows / Web Services, etc using rich graphical user interface for all platforms supported by Microsoft. Visual Studio supports different programming languages by means of language services. The Most Preferred Built-in languages include VC++.NET, Visual Basic .NET, C#.NET. Support for other languages such as J#, M, Python, Perl and Ruby among others is available via language services installed separately. It also supports XML/XSLT, HTML/ XHTML, JavaScript and CSS. What is .NET FrameWork ? The .NET Framework is a software environment responsible for the EXECUTION of code written in any of the languages supported by .NET (VB, C#, J#, VC++, etc). The .NET Framework must reside on the machine where the code is to be executed. .NET Framework, is installed as a part of Visual Studio .NET or can also be installed independently from Microsoft’s website. It is also in-built with Windows Operating systems. Prior to .Net: Microsoft has produced visual studio 6.0 (VB 6, C#, ASP) with classic ASP for developing web base application but there are several drawbacks in this project. Microsoft start a new project with code name Next Generation Windows Services (NGWS) 1 VB.Net…

VBdotnet Introduction

Embed Size (px)

DESCRIPTION

A brief introduction to VB.NEt

Citation preview

Page 1: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Introduction to Visual Studio .NET: Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It can be used to develop console applications, Windows applications, Web applications, Mobile Applications, Windows / Web Services, etc using rich graphical user interface for all platforms supported by Microsoft. Visual Studio supports different programming languages by means of language services. The Most Preferred Built-in languages include VC++.NET, Visual Basic .NET, C#.NET. Support for other languages such as J#, M, Python, Perl and Ruby among others is available via language services installed separately. It also supports XML/XSLT, HTML/XHTML, JavaScript and CSS.

What is .NET FrameWork ? The .NET Framework is a software environment responsible for the EXECUTION of code written in any of the languages supported by .NET (VB, C#, J#, VC++, etc). The .NET Framework must reside on the machine where the code is to be executed. .NET Framework, is installed as a part of Visual Studio .NET or can also be installed independently from Microsoft’s website. It is also in-built with Windows Operating systems. Prior to .Net: Microsoft has produced visual studio 6.0 (VB 6, C#, ASP) with classic ASP

for developing web base application but there are several drawbacks in this project.

Microsoft start a new project with code name Next Generation Windows Services (NGWS)

1

VB.Net…

Page 2: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

which was later named as .Net.

MICROSOFT .NET FRAMEWORK Microsoft .Net framework is an integrated and managed environment for the development and execution of your code. The .Net Framework includes two main components:

1. The .Net Base Class Library.2. The Common Language Runtime (CRL).

2

VB.Net…

Page 3: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

3

VB.Net…

Page 4: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

The .Net Base Class Library: The .Net base class library is a collection of object oriented classes and interfaces that provides object model and services for many complex programming tasks. The logical group of all these in-built classes and interfaces is called as a Namespace. i.e.: A Namespace is collection of classes. Some of the most important .Net Base Class Libraries are:

SystemSystem.ioSystem.dataSystem.xmlSystem.windows.formSystem.collectionsEtc.

The Common Language Runtime (CRL): The Common Language Runtime (CLR) manages code at runtime. CLR as the name specifies, provides a common environment for programs written in different languages supported for .Net like VB, C#, VC++, J#, Perl, Python, etc. It offer INTEROPERABILITY between programs written in different languages i.e. An Application can have different modules written in different programming languages supported by .Net. CRL is a component divided in sub components which perform their own respective tasks. The components of CRL are: a. Common Type System (CTS):

CTS is the major component of CRL. Its purpose is to provide data types conversion / consistency between different languages of .net to ensure interoperability. A subset of CTS is Common Language Specification (CLS) which also provides functionality to support interoperability.

b. Just in time Compiler (JIT):

When a .Net Program is compiled, an executable file is generated. This .exe file is in Microsoft Intermediate Language (MSIL). When the program is used / executed, then JIT compiler compiles only the required code, as it is visited in native (OS) form. This feature of .Net allows the programs to be Platform Independent.

4

VB.Net…

Page 5: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

As .Net has multiple languages, we require an appropriate language compiler

specific for the language. All the compilers, after conversion of the source code, will

generate the same type of code i.e. MSIL code which will be converted into machine code

for execution. As all the .Net languages after compilation were generating the same type

of code (IL). The code of one language can be consumed from any other .Net language.

This Feature of .NET is Called “Language Interoperability” or language independency.

c. Garbage Collection (GC):

Garbage Collector is a background thread running with the application / CLR and is responsible for destroying all the unreferenced objects i.e. objects which are no longer in use.

d. Class Loader:

It is a Sub Component in CLR and is responsible for loading classes and other types as and when needed.

e. Security Manager:

Security Manager is a component of CLR. There are the types of security models supported in .Net:

i. Code Access Security (CAS).ii. Role Based Security.iii. ASP.Net Web Application Security.

The Security Manager decides whether or not a piece of code is allowed to run. It will prevent malicious code from entering your system and causing damage.

f. Assemblies:

An Assembly is a self describing collection of code, resource, and metadata. An Assembly manifest contains information about what is contained in the assembly like:

i. Assembly’s name and version number.ii. List of all the TYPES used by the program.iii. List of other assemblies, if any.iv. Security Details.

Framework Versions Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.

5

VB.Net…

Page 6: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

1. MICROSOFT .NET FRAMEWORK

1 CLR : It is the core component of the framework which is

responsible for converting the IL code into machine code.

2 BCL : It is a set of libraries functionalities which have been

provided common to all .Net languages.

3 Win Forms : Win Forms are to be used in the development of graphical

user interface (Windows application).

4 ASP.Net : It is used in the development of web applications using .Net

languages.

5 WPF : (Windows Presentation Foundation ) : It is same of as Win

Form used in the development of GUI applications but provides

the support for graphics, animation, 2D, 3D image which was

not provided under traditional Win Forms Technology)

6 WCF : (Windows Communication Foundation): This is used in the

development of distributed application.

7 LINQ : (Language Integrated Query): It is also used for interacting

with databases similar to ADO.Net.

8 ADO.Net : ADO.Net entity Framework is an extension for traditional

ADO.

6

VB.Net…

Page 7: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

The .NET Framework

Version Version Number Release Date Visual Studio Default in Windows

1.0 1.0.3705.0 2002-02-13 Visual Studio .NET

1.1 1.1.4322.573 2003-04-24 Visual Studio .NET 2003 Windows Server 2003

2.0 2.0.50727.42 2005-11-07 Visual Studio 2005

3.0 3.0.4506.30 2006-11-06 Windows Vista, Windows Server 2008

3.5 3.5.21022.8 2007-11-19 Visual Studio 2008 Windows 7

7

VB.Net…

Page 8: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

2. DATA TYPES IN .NET

1. Value Type

2. Reference Type

1. VALUE TYPE:

i. Integer Types:

Data Type Size

Byte 1

Sbyte 1

Short 2

Ushort 2

Integer 4

Uinteger 4

Long 8

Ulong 8

ii. Floating Types:

Data Types Size

Single 4

Double 8

Decimal 16

iii. Other Data Types:

Data Types Size

Char 2

Boolean 2

Date 8

iv. Reference Types: Eg: Object, Strings, Arrays, etc.

8

VB.Net…

Page 9: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

9

VB.Net…

Page 10: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

3. OPERATORS

Arithmetic Operators:

Operator Function

^ Power of an exponent

* Multiplication

\ Divide two numbers and returns integer

/ Divide two numbers and returns float

Mod Remainder of the equation

+ Addition

- subtraction

Comparison Operators:

Operator Usage

< exp1 < exp2

> exp1 > exp2

<= Exp1 <= exp2

>= Exp1 >= exp2

= Exp1 = exp2

<> Exp1 <> exp2

Assignment Operators:

Operator Usage

= Variable = value

*= Multiplication and assignment

/= Div & assign (float)

\= Div & assign (integer)

+= Add & assign

-= Sub & assign

&= Concatenates a string exp to a string variable

Logical Operators:

Ø AND

10

VB.Net…

Page 11: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Ø ORØ NOT

11

VB.Net…

Page 12: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

4. STATEMENTS

If Demo Output

Select Demo Output

For Demo Output

12

VB.Net…

Page 13: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

13

VB.Net…

Page 14: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class Frm_Demo_if Dim total As IntegerDim per As SingleDim result As String Private Sub btn_result_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_result.Click total = CInt(txtMarks1.Text) + CInt(txtMarks2.Text) + CInt(txtMarks3.Text)per = (total * 100) / 300If per < 35 Thenresult = "FAIL"Elseresult = "PASS"End IfMsgbox("Total : " + CStr(total) + vbCrLf + "Per : " + CStr(per) + vbCrLf + "Result : " + result) End SubEnd Class Public Class frm_for_table Dim n As IntegerDim str As StringDim i As Integer Private Sub btn_table_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_table.Click

str = ""n = CInt(txttable.Text)For i = 1 To 10str &= CStr(n) + " X " + CStr(i) + " = " + CStr(n * i) + vbCrLfNextMsgBox(str) End SubEnd Class Public Class frm_demo_select Private Sub Btn_Percentage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Percentage.Click Select Case (txtgrade.Text.ToUpper)Case "A"MsgBox("The Percentage is above 75%")Case "B"MsgBox("The Percentage is between 65 % AND 75%")Case "C"MsgBox("The Percentage is Between 40% & 65%")Case "D"MsgBox("The Percentage is below 40%")Case ElseMsgBox("Invalid char...please enter A,B,C or D") End Select End SubEnd Class

14

VB.Net…

Page 15: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

5. STRUCTURE DEMO OUTPUT

Public Class frm_structure_demo Public Structure studDim n As StringDim p As IntegerDim c As IntegerDim m As IntegerEnd Structure Dim s1 As stud Private Sub frm_structure_demo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load txtphy.Enabled = Falsetxtchem.Enabled = Falsetxtmaths.Enabled = Falsetxtname.Enabled = False End Sub Private Sub btn_new_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_new.Click txtphy.Enabled = Truetxtchem.Enabled = True

txtmaths.Enabled = Truetxtname.Enabled = Truetxtphy.Clear()txtchem.Clear()txtmaths.Clear()txtname.Clear()txtname.Focus() End Sub Private Sub btn_getresult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_getresult.Click Dim tot As IntegerDim per As Single s1.n = txtname.Texts1.p = CInt(txtphy.Text)s1.c = CInt(txtchem.Text)s1.m = CInt(txtmaths.Text) tot = s1.c + s1.p + s1.mper = (tot * 100) / 300 MsgBox("Name = " + s1.n + vbCrLf + "Total = " + tot.ToString + vbCrLf + "Per = " + per.ToString) End Sub End Class

15

VB.Net…

Page 16: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16

VB.Net…

Page 17: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

6. ARRAY DEMO OUTPUT

Public Class frm_array_demo Dim s(5) As StringDim str As StringDim a As String Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click s(0) = txtname1.Texts(1) = txtname2.Texts(2) = txtname3.Texts(3) = txtname4.Texts(4) = txtname5.Texts(5) = txtname6.Text MsgBox("The Length of Array S is " + s.Length.ToString) For Each a In sstr &= a + vbCrLfNext MsgBox(str, , "Member of The Array") End Sub

Private Sub btnsort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsort.Click Array.Sort(s)str = ""For Each a In sstr &= a + vbCrLfNextMsgBox(str, , "Sorted Member of The Array") End Sub Private Sub btnreverse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreverse.ClickArray.Reverse(s)str = ""For Each a In sstr &= a + vbCrLfNextMsgBox(str, , "Reversed Member of The Array") End Sub End Class

17

VB.Net…

Page 18: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

7. DYNAMIC ARRAY OUTPUT

Public Class frm_dynamic_array Dim s() As StringDim i As Integer = 0 Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click ReDim s(CInt(TxtNumber.Text)) End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click For i = 0 To s.Length - 1s(i) = InputBox("Enter name " + (i + 1).ToString)Next End Sub

Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click Dim str As String = ""Dim i As Integer = 0 For i = 0 To s.Length - 1str &= s(i) + vbCrLfNextMsgBox(str) End Sub End Class

18

VB.Net…

Page 19: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

8. CALL BY VALUE & CALL BY REFERENCE

‘Demo of Call by Val & Call by Reference Public Class Form1 Dim l As IntegerDim m As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click l = CInt(TextBox1.Text)m = CInt(TextBox2.Text) func_add(l, m) TextBox1.Text = lTextBox2.Text = m End Sub Public Sub func_add(ByVal a As Integer, ByRef b As Integer)a += 1b += 1 End Sub

19

VB.Net…

Page 20: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Class

20

VB.Net…

Page 21: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

9. EXCEPTION HANDLING

§ Exceptions are runtime error cause due to a logical error, S/W error or limitation

of the hardware.

§ In .Net, every exception is an object of type system.exception or any of its sub

classes.

§ When the integrity on an object is violated, an exception is raised.

§ Exception Handling is done by providing try … catch blocks.

§ If an exception is thrown and is unhandled is an inner block then it is automatically

thrown to its outer block. If an exception is unhandled, then the CLR terminated

the program abruptly.

§ For one Try block, we can have multiple catch blocks, each for a specific

exception.

§ Finally block may be written to execute all the necessary code to execute before

exiting the program, in case of exception or no exception.

21

VB.Net…

Page 22: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class txtvalue2 Dim a As IntegerDim b As IntegerDim c As Integer Private Sub btnDivide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDivide.Click Trya = CInt(txtvalue1.Text)b = CInt(TextBox2.Text)c = a / bMsgBox(c.ToString)Catch ex As InvalidCastExceptionMsgBox(ex.Message & vbCrLf & "Enter Valid Data")Catch ex As ExceptionMsgBox(ex.Message)Finallytxtvalue1.Text = ""TextBox2.Text = ""txtvalue1.Focus() End Try End SubEnd Class

22

VB.Net…

Page 23: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

VB.NET – OOP’s Guide

Object Oriented Programming Structure (OOPS)

The programming in which data will be logically represented in the form of a class

and physically represented in the form of an object is called as object oriented

programming.

OOP’S has following important features:

1. Class:-

According to oop’s data must be represent in the form of class. A class can contain

variables for storing the data and function to specify various operations that can perform

on data. Class doesn’t occupy any memory space hence it’s only logical representation of

data. Object oriented programming features are taken from real life. In a real life a plan

will be drawn before constructing any object the same is implemented in oop’s with the

form of class.

A class is like a plan or blueprint for the data of your program.

2. Data Encapsulation & Abstraction:

A Class can contain variables for storing the data and functions to specify various

operations that can be performed on data. This process of wrapping of data and

functions that operate on that data as a single unit in the form of class is called as data

encapsulation. Advantage of encapsulation is hiding the implementation detail of class.

In real life if you take CPU of system , it is encapsulation of various component like

motherboard, Ram, Hard Disk and Other hardware to use the CPU no need to have the

knowledge how exactly all this component are working internally the same is

implemented in oop’s in the form of data encapsulation. Abstraction is the process hiding

details of class when member of a class are declared as private when it is not possible to

access them from outside the class.

23

VB.Net…

Page 24: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Advantages of this are security in the real life all the components of CPU are

enclosed in a cabinet to protect them from the dust same is implemented in oops in the

form of abstraction.

Object and Instance:

Object with keyword

New

Stack

Heap

Permanent Memory

A class is a only a logical representation of data hence to work with the data

represented by the class you must declare variable for the class, which is called as an

object when an object is declared using the keyword “new” then memory will be

allocated for the members of the class within the heap memory area which is called as

Instance & it’s address will be stored in the object in stack.

When an object is created without using the keyword “new” then instance will not

be created and object in stack will contain Null. In this case it’s not possible to access the

members of the class by using that object because the object contains Null.

Constructor

1. A constructor is a special method present under every class responsible for

initializing the variable of the class.

2. A constructor is a non value returning method and will have the same name of

class.

3. A constructor is mandatory under every class is the class has to execute.

Note: where out C# compiler compiles the program it verifies whether the class

contains the constructor in it or not. If not present the class can not execute so

on behalf of the programmer the compiler takes the responsibility in defining a

constructor under the program so that class can execute.

24

VB.Net…

Page 25: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

4. Constructor is special method in the class that will be automatically invoked while

an instance is created for the class it’s main purpose is to initialize the fields available

in the class while instance is created.

But you can write “any code” that needs to be executed while an instance is created.

When you are not creating constructor in the class than compiler will automatically

create a default constructor that will initialize fields in the class to the default value

based data type.

To create a constructor in the class in the vb.net create a “sub procedure” in the

class with the name “new”.

Type of constructor:

1. Default constructor: - A constructor without any parameters is called as a default

constructor. A drawback of default constructor is any no of instances you create

for the class, all the instances will be unitized to same value and it’s not possible

to initialize each instance of the class to different values.

2. Parameterized Constructor: A constructor with at least one parameter is called as

parameterized constructor “advantage of this is each instance of the class can be

initialized to deferent value.”

3. Copy constructor: In parameterized constructor with a parameter of same class

type is called as copy constructor. Purpose of copy constructor is to copy the

values of an existence instance to the new instance.

4. Shared Constructor: You can also declare a constructor as shared but a shared

constructor will be invoked only once for any once for any no of instances created

for the class. A shared constructor will be invoked in any of the following situation.

1) When first instance is created for the class.

2) When you referred to a shared member in the class for the first time.

Shared constructor is used to write the code that’s need to be executed only once.

5. Private Constructor:

Constructor can also be created as private but when there is at least ne private

25

VB.Net…

Page 26: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

constructor available in the class create an instance for the class will not be possible.

Purpose of privat3e constructor is to restrict the class form being instantiate when the

class contains every member as shared. Point Related to Constructor

1. A class can have any no of constructors in the class provided they satisfy method

overloading rule.

2. A class can have only one shared constructor or and shared constructed can’t

parameterized.

3. Constructor must be a sub-procedure and can’t be a function procedure.

Destructor

Destructor is a special method in the class that will be automatically invoked while

an instance of the class is destroyed. Destructor is used to write the code that needs

to be executed while an instance of the class is destroyed when you are not creating

a destructor in the class than compiler will not destructor automatically, to create a

destructor within a class in VB.net , create sub-procedure with the name finalize that has

following syntax.

Protected overrides sub finalize

<Statement>

End sub

By default every class in .Net is inherited from a class called as “Object” even your

are not specifying to inherit explicitly within this object class the finalize method is

overridable method and declared with the access modifier protected. Creating finalize

method your calss is nothing but the overriding the finalize method of base class hence it

must be declared with the keyword overrides.

To make the destructor available only within the same class and it’s derived

classes but not from outside the class it must be declared as protected.

26

VB.Net…

Page 27: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

In .Net object will not be destroyed immediately after their lifetime is expired.

And they will be destroyed only when garbage collector performs garbage collection.

Garbage collector will perform garbage collection only in the following two

situations.

1. When there is not enough memory to create a new object.

2. When your application comes to an end.

When you don’t want to wait until the garbage collector performs garbage collection

then you can force the garbage collector to perform garbage collection by calling collect

method of GC class. But this is not recommended as if affects the performance of the

application.

Point about destructor:

1. A Class can have only one destructor.

2. Destructor must be a sub procedure can’t possible to create it as function.

3. Destructor cannot be parameterized.

4. Destructor cannot be shared.

10. OOPS – Classes, Objects, Constructors & Destructors

Public Class Accounts

Private accno As Integer

Private acc_name As String

Private bal As Integer

27

VB.Net…

Page 28: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

'Constructor

Public Sub New()

MsgBox("Objected Created")

End Sub

'Public Method to Populate Above Three Private Varaible

Public Sub setdata(ByVal a As Integer, ByVal b As String, ByVal c

As Integer)

Me.accno = a

Me.acc_name = b

Me.bal = c

End Sub

'Public Method to Display msgbox as output

Public Sub getdata()

MsgBox(Me.accno.ToString + vbNewLine + Me.acc_name + vbNewLine +

Me.bal.ToString)

End Sub

'Destructor

Protected Overrides Sub finalize()

MsgBox("Objected Destroyed")

End Sub

End Class

Public Class Frm_OOP_Demo_1

'Declaring the Obj. of Class Account

Dim obj As Accounts

Private Sub btn_Create_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles btn_Create.Click

'Initializing The Object obj on class Accounts

obj = New Accounts

End Sub

Private Sub btn_set_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btn_set.Click

'Sending the Values from textboxs to Accounts Class Through Method

SetData

obj.setdata(CInt(txtaccno.Text), txtname.Text, CInt(txtbalance.Text))

End Sub

Private Sub btn_get_Click(ByVal sender As System.Object, ByVal e As

28

VB.Net…

Page 29: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

System.EventArgs) Handles btn_get.Click

'Calling the Method Getdata to view the Output

obj.getdata()

End Sub

Private Sub btn_destroy_Click(ByVal sender As System.Object, ByVal

e As System.EventArgs) Handles btn_destroy.Click

'Calling The Destructor

obj = Nothing

End Sub

End Class

29

VB.Net…

Page 30: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

11. OOPS – PROPERTIES

30

VB.Net…

Page 31: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class Accounts

Private Shared accno As

Integer = 0

Private accname As String

Private bal As Integer

Private minbal As Integer

Public Sub New()

MsgBox("Object Created")

accno += 1

End Sub

Public Property

pro_accname()

Get

Return Me.accname

End Get

Set(ByVal value)

Me.accname = value

End Set

End Property

Public Property pro_bal()

Get

Return Me.bal

End Get

Set(ByVal value)

Me.bal = value

End Set

End Property

Public WriteOnly Property pro_minbal()

Set(ByVal value)

Me.minbal = value

End Set

End Property

Public ReadOnly Property pro_accno()

Get

Return accno

End Get

End Property

Public Sub desposit(ByVal a As

Integer)

Me.bal += a

End Sub

Public Sub withdraw(ByVal a As

Integer)

If Me.bal - a < Me.minbal Then

MsgBox("Insufficient Balance")

Else

Me.bal -= a

End If

End Sub

Protected Overrides Sub finalize()

MsgBox("Objects Destroyed")

End Sub

End Class

Public Class Frm_OOP_Demo

Dim acc1 As Accounts

Private Sub btn_create_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles btn_create.Click

acc1 = New Accounts

txtno.Text = acc1.pro_accno

End Sub

31

VB.Net…

Page 32: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btn_set_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btn_set.Click

acc1.pro_accname = txtname.Text

acc1.pro_bal = CInt(txtbal.Text)

acc1.pro_minbal = CInt(txtminbal.Text)

End Sub

Private Sub btn_get_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btn_get.Click

MsgBox(acc1.pro_accno.ToString + vbCrLf + acc1.pro_accname + vbCrLf

+ acc1.pro_bal.ToString)

End Sub

Private Sub btn_deposit_Click(ByVal sender As System.Object, ByVal

e As System.EventArgs) Handles btn_deposit.Click

acc1.desposit(CInt(txtamt.Text))

txtbal.Text = acc1.pro_bal

End Sub

Private Sub btn_withdraw_Click(ByVal sender As System.Object, ByVal

e As System.EventArgs) Handles btn_withdraw.Click

acc1.withdraw(CInt(txtamt.Text))

txtbal.Text = acc1.pro_bal

End Sub

End Class

32

VB.Net…

Page 33: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

12. OOPS – INHERITANCE

12.1 Inheritance: While creating a new class if it requires same members as existing class then

instead of re-creating those members you can create the new class from an existing class.

This process of creating a new class from an existing class is called as inheritance.

Advantage of inheritance is code reusability. During inheritance the class that is inherited

is called as base class and the class that does the inheritance is called as derived class or

child class and every non private member of the base class will become the member of

derive class with the same access modifier as in base class.

To perform inheritance, you have to use the keyword inherits and it’s has the following

syntax.

[Access modifier] class<class name> inherits <BaseClass_name>

<Member>

End class

Inheritance allows you to create a new class that retains all the members and Functionalities of a previously defined class. This feature of OOP allows code reusability.

33

VB.Net…

Public Class stud_info

public sno As Integer

public sname As String

public address As String

End Class

Public Class mca Inherits stud_info

Public os As Integer

Public dbms As Integer

Public c As Integer

Public Sub result()

Dim tot As Integer

Dim per As Decimal

Dim str As String

Dim res As String

tot = me.os + me.dbms + me.c

per = CDec((tot * 100) / 300)

If per < 40 Then

res = "FAIL"

Else

res = "PASS"

End If

str &= Me.sno.ToString + vbCrLf

str &= Me.sname + vbCrLf

str &= Me.address + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str,,”MCA RESULT”)

End SubEnd Class

Public Class mba Inherits stud_info

Public fin As Integer

Public hr As Integer

Public mkt As Integer

Public Sub result()

Dim tot As Integer

Dim per As Decimal

Dim str As String

Dim res As String

tot = me.fin + me.hr + me.mkt

per = CDec((tot * 100) / 300)

If per < 50 Then

res = "FAIL"

Else

res = "PASS"

End If

str &= Me.sno.ToString + vbCrLf

str &= Me.sname + vbCrLf

str &= Me.address + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str,,”MBA RESULT”)

End SubEnd Class

Page 34: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class frm_inheritance_Demo

Dim s1 As mca

Dim s2 As mba

Private Sub btnNewMCA_Click (ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnNewMCA.Click

s1 = New mca

Label4.Text = "OS"

Label5.Text = "DBMS"

Label6.Text = "C"

txtsno.Focus()

End Sub

Private Sub btnMCAsave_Click (ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnMCAsave.Click

'saving info to MCA obj

s1.sno = CInt(txtsno.Text)

s1.sname = txtsname.Text

s1.address = txtaddress.Text

s1.os = CInt(txtmark1.Text)

s1.dbms = CInt(txtmark2.Text)

s1.c = CInt(txtmark3.Text)

End Sub

Private Sub btnMCAResult_Click (ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnMCAResult.Click

s1.result()

End Sub

Private Sub btnNewMBA_Click (ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Click

s2 = New mba

Label4.Text = "FIN"

Label5.Text = "HR"

Label6.Text = "MKT"

txtsno.Focus()

End Sub

PrivateSub btnMBAsave_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMBAsave.Click

'saving info to MBA obj

s2.sno = CInt(txtsno.Text)

s2.sname = txtsname.Text

s2.address = txtaddress.Text

s2.fin = CInt(txtmark1.Text)

s2.hr = CInt(txtmark2.Text)

s2.mkt = CInt(txtmark3.Text)

End Sub

Private Sub btnMBAResult_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Click

s2.result()

End Sub

End Class

34

VB.Net…

Page 35: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Type of Inheritance

1. Single Inheritance: The inheritance in which a single derived class is created from a

single base class is called as single inheritance.

2. Hierarchical Inheritance: - The inheritance in which more than one derived class is

created from a single base class is called as hierarchical inheritance.

3. Multilevel inheritance: - The inheritance in which a derived class is created from

another derived class is called as multilevel inheritance.

4. Hybrid Inheritance: - The inheritance i.e. the combination of hierarchical and

multilevel inheritances is called as hybrid inheritance.

35

VB.Net…

Page 36: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

5. Multiple Inheritances: - The inheritance in which a single derived class is created from

multiple base classes is called as multiple inheritances.

Note: multiple inheritances not supported by .net using classes and it’s supported

using interface. During multiple inheritance if more than one base class contain

members with same signature then derived class will get more than one member with

same signature, which is not actually possible overcome this problem c++ use virtual

base class concept that internal requires pointers but .net doesn’t support pointers

and hence if cannot provide virtual base class concept and hence multiple inheritance

was not supports.

36

VB.Net…

Page 37: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

13. OOPS – MustInherit Class & Method Overriding

MustInherit (Abstract Classes): when a Class is Defined as Mustinherit, then an object cannot be created directly on that class, and it must have a derived class through which it’s member will be accessed. Method Overriding:

a. Notoverridable (Default): A Method of the base class, which cannot be overridden in the derived classes.

b. Overridable: A Method of the base class, that MAY have a new implementation in the derived class.

c. Mustoverride: A Method of the base class, which MUST have a new implementation in the derived class. This method can only be declared in a Mustinherit class.

d. Override: A Method of the base class, which overrides the method of its base class.

37

VB.Net…

Page 38: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

38

VB.Net…

Public MustInherit Class stud_info

Protected sno As Integer

Protected sname As String

Protected address As String

Public MustOverride Sub marks(a as integer, b as string, c as string, m1

as integer, m2 as integer, m3 as integer)

Public MustOverride sub result()

End Class

Public Class mca Inherits stud_info

private os,dbnms,c As Integer

Public Overrides Sub marks(a as integer, b as string, c as string, m1 as integer, m2 as integer, m3 as integer)

Me.sno = a

Me.sname = b

Me.address = c

Me.os = m1

Me.dbms = m2

Me.c = m3

End sub Public Overrides Sub result()

Dim tot As Integer

Dim per As single

Dim str,res As String

tot = me.os + me.dbms + me.c

per = CDec((tot * 100) / 300)

If per < 40 Then

res = "FAIL"

Else

res = "PASS"

End If

str &= Me.sno.ToString + vbCrLf

str &= Me.sname + vbCrLf

str &= Me.address + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str)

End Sub

END CLASS

Public Class mbaInherits stud_info

private fin,hr,mkt As Integer

Public Overrides Sub marks(a as integer,b as string,c as string,m1 as integer,m2 as integer,m3 as integer)

Me.sno = a

Me.sname = b

Me.address = c

Me.fin = m1

Me.hr = m2

Me.mkt = m3

End sub

Public Overrides Sub result()

Dim tot As Integer

Dim per As single

Dim str,res As String

tot = me.fin + me.hr + me.mkt

per = CDec((tot * 100) / 300)

If per < 50 Then

res = "FAIL"

Else

res = "PASS"

End If

str &= Me.sno.ToString + vbCrLf

str &= Me.sname + vbCrLf

str &= Me.address + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str)

End SubEnd Class

Page 39: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class frm_inheritance_Demo

Dim s1 As mca

Dim s2 As mba

Private Sub btnNewMCA_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnNewMCA.Click

s1 = New mca

Label4.Text = "OS"

Label5.Text = "DBMS"

Label6.Text = "C"

txtsno.Focus()

End Sub

Private Sub btnMCAsave_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnMCAsave.Click

'saving info to MCA obj

S1.marks(CInt(txtsno.Text),

txtsname.Text,

txtaddress.Text,

CInt(txtmark1.Text),

CInt(txtmark2.Text),

CInt(txtmark3.Text))

End Sub

Private Sub btnMCAResult_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnMCAResult.Click

s1.result()

End Sub

Private Sub btnNewMBA_Click(ByVal sender As System.Object, ByVal e

AsSystem.EventArgs) Handles Click

s2 = New mba

Label4.Text = "FIN"

Label5.Text = "HR"

Label6.Text = "MKT"

txtsno.Focus()

End Sub

Private Sub btnMBAsave_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles Click

'saving info to MBA obj

S2.marks(CInt(txtsno.Text),

txtsname.Text,

txtaddress.Text,

CInt(txtmark1.Text),

CInt(txtmark2.Text),

CInt(txtmark3.Text))

End Sub

Private Sub btnMBAResult_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles Click

s2.result()

End Sub

End Class

39

VB.Net…

Page 40: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

14. OOPS - INTERFACE

An interface is nothing but the user defined data type that can contain only

declarations and not definition. Main purpose of interface is to provide contract for

the class must provide definition for a set of members. To create an interface use the

keyword interface that has the following syntax.

[Access modifier] interface <interface > <interface name>

<Interface members>

End interface

While creating an interface, consider the following points.

1) An Interface can contain only declarations and it’s not possible to define any member

in the interface.

2) Interface can’t contain field.

3) It is not possible to specify access modifier for the members of an interface and every

member in interface is public by default.

4) It is not possible to declare the member of an interface as shared.

To implement interfaces in a class use the keyword “implement ” and it has the following

syntax

[access modifier]classname :implements <interface1><interface2>,……

<member>

End class

One class can implement any no of interfaces and one interface can be implemented by

any no of classes. But when a class implements an interface them it must provide the

definition for every member in the interface otherwise it will be a compilation error.

There may be a situation where more than one interface contain a member with same

signature and those interfaces are implemented in the same class.

In this case to resolve the ambiguity, simple solution is rename one of those

40

VB.Net…

Page 41: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

method of class while they are defined. Even the method was rename compiler will

identify to which method which interface the definition belongs based on implementa

statement at the end of that method of declaration within the class.

• An interface is a collection of related methods and properties without

implementation.

• An interface is a point of contact with an object.

• An interface is equal to a Mustinherit Class with all members declared as

Mustoverride.

• We can implements multiple inheritance and multilevel inheritance with the help

of interfaces.

41

VB.Net…

Page 42: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Interface Istud

Sub stud_info(ByVal n As String, ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)

Sub result()

End Interface

Public Class mca Implements Istud

Private sname As String

Private os As Integer

Private dbms As Integer

Private c As Integer

Public Sub stud_info(ByVal n As String, ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)

Implements Istud.stud_info

Me.sname = n

Me.os = a

Me.dbms = b

Me.c = c

End Sub

Public Sub result() Implements Istud.result

Dim tot As Integer

Dim per As Decimal

Dim str As String = ""

Dim res As String = "PASS"

tot = Me.os + Me.dbms + Me.c

per = CDec((tot * 100) / 300)

If per < 40 Then

res = "FAIL"

End If

str &= Me.sname + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str)

End SubEnd Class

Public Class mba Implements Istud

Private sname As String

Private fin As Integer

Private hr As Integer

Private mkt As Integer

Public Sub stud_info(ByVal n As String, ByVal a As Integer,

ByVal b As Integer, ByVal c As Integer)

Implements Istud.stud_info

Me.sname = n

Me.fin = a

Me.hr = b

Me.mkt = c

End Sub Public Sub result() Implements Istud.result

Dim tot As Integer

Dim per As Decimal

Dim str As String = ""

Dim res As String = "PASS"

tot = Me.fin + Me.hr + Me.mkt

per = CDec((tot * 100) / 300)

If per < 50 Then

res = "FAIL"

End If

str &= Me.sname + vbCrLf

str &= tot.ToString + vbCrLf

str &= per.ToString + vbCrLf

str &= res

MsgBox(str)

End Sub End Class

42

VB.Net…

Page 43: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class frm_Interface_Demo

Dim s As Istud

Private Sub btnNewMCA_Click(ByVal

sender As System.Object, ByVal

e As System.EventArgs) Handles

btnNewMCA.Click

s = New mca

End Sub

Private Sub btnMCASave_Click

(ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles btnMCASave.Click

s.stud_info(txtname.Text,

CInt(txtmarks1.Text),

CInt(txtmarks2.Text),

CInt(txtmarks3.Text))

End Sub

Private Sub btnMCAResult_Click

(ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles btnMCAResult.Click

s.result()

End Sub

Private Sub btnNewMBA_Click

(ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles

btnNewMBA.Click

s = New mba

End Sub

Private Sub btnMBASave_Click

(ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles btnMBASave.Click

s.stud_info(txtname.Text,

CInt(txtmarks1.Text),

CInt(txtmarks2.Text),

CInt(txtmarks3.Text))

End Sub

Private Sub btnMBAResult_Click

(ByVal sender As System.Object,

ByVal e As System.EventArgs)

Handles btnMBAResult.Click

s.result()

End Sub

End Class

43

VB.Net…

Page 44: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

15. OOPS - METHOD OVERLOADING

Methods are procedures that contain application logic. Methods in VB.NET can be either:

1. Sub Procedures

2. Functions

A Method created with sub does not return a value. A Method create with function must

return a value.

Parameters to methods are declared as Byval by default, but it may also be ByRef.

44

VB.Net…

Page 45: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class cal

Public Sub welcome()

MsgBox("Welcome")

End Sub

Public Function add(ByVal a As

Integer, ByVal b As Integer) As

Integer

Return a + b

End Function

Public Function add(ByVal a As

Decimal, ByVal b As Decimal) As

Decimal

Return a + b

End Function

Public Function add(ByVal a As

String, ByVal b As String) As

String

Return a + b

End Function

End Clas

Public Class frm_func_overloading

Dim obj As cal

Dim i As Integer

Dim d As Decimal

Dim s As String

Private Sub btnAdd_Click(ByVal

sender As System.Object, ByVal

e As System.EventArgs) Handles

btnAdd.Click

obj = New cal

obj.welcome()

If rdointerger.Checked = True

Then

i = Obj.add(CInt(txtvalue1.Text),

CInt(txtvalue2.Text))

MsgBox(i.ToString)

ElseIf rdodecimal.Checked = True

Then

d = obj.add(CDec(txtvalue1.Text),

CDec(txtvalue2.Text))

MsgBox(d.ToString)

ElseIf rdostring.Checked = True

Then

s = obj.add(txtvalue1.Text,

txtvalue2.Text)

MsgBox(s)

Else

MsgBox("Please Select One

Option")

End If

End Sub

End Class

45

VB.Net…

Page 46: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16. OOP - Multiple Inheritance Demo

Public Class stud

Protected sno As IntegerProtected sname As StringProtected address As String Public Sub set_data(ByVal a As Integer, ByVal b As String, ByVal c As String) Me.sno = aMe.sname = bMe.address = c End SubEnd Class Public Interface Isem_1 Sub marks(ByVal c As Integer, ByVal os As Integer, ByVal dbms As Integer) Sub result()End Interface

Public Class mca Inherits stud Implements Isem_1 Dim tot As IntegerDim per As SingleDim res As StringDim str As String Public Sub marks(ByVal c As Integer, ByVal os As Integer, ByVal dbms As Integer) Implements Isem_1.marks tot = c + os + dbmsper = CDec((tot * 100) / 300)If per < 40 Thenres = "FAIL"Elseres = "PASS"End IfEnd Sub Public Sub result() Implements Isem_1.result str = ""str &= Me.sno.ToString + vbNewLinestr &= Me.sname + vbNewLinestr &= Me.address + vbNewLinestr &= tot.ToString + vbNewLinestr &= per.ToString + vbNewLinestr &= res MsgBox(str, , "MCA I-Sem Result")

46

VB.Net…

Page 47: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End SubEnd Class

Public Class Frm_Multiple_Inheritence Dim obj As mca Private Sub btn_new_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_new.Click obj = New mca End Sub Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click obj.set_data(CInt(TextBox1.Text), TextBox2.Text, TextBox3.Text)obj.marks(CInt(TextBox4.Text), CInt(TextBox5.Text), CInt(TextBox6.Text)) End Sub Private Sub btn_result_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_result.Click obj.result() End SubEnd Class

47

VB.Net…

Page 48: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

VB.NET – User Interface Guide15. DESIGNING & DEVELOPING USER INTERFACE

1. FORM

Properties:

Name, Text, Backcolor, BackgroundImage, Cursor, Font, Forecolor, Opacity, Startupposition, Windowstate, etc

Events:

Load, Activated, Deactivate, Click, DoubleClick, FormClosing, Formclosed, Keypress, MouseEnter, MouseLeave, etc

Methods:

Close, CentertoScreen, resettext, show, showdialog, hide, etc 2. LABEL

Properties

Name, Autosize, Backcolor, Borderstyle, Font, Forecolor, Image, Text, Visible, Etc. Events:

Click, Leave, etc. Methods

Focus, hide, show, resettext, tostring 3. TEXT BOX:

Properties:

Name, Autosize, AutoCompleteCustomSource, AutoCompleteMode, AutoCompleteSource, Backcolor, Borderstyle, Font, Forecolor, Multiline, Readonly, PasswordChar, text, etc

Events:Click, Enter, Leave, Keypress, Keydown, Keyup, TextChanged, etc

Methods:

Clear, Copy, Cut, Paste, Focus, Hide, Show, etc 4. COMMAND BUTTON

Properties:

Name, Backcolor, BackgroundImage, FlatStyle, Font, ForeColor, Text, Enabled, Visible.

48

VB.Net…

Page 49: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Events:

Click, Enter, Leave, Etc Methods:

Focus, Hide, Show, etc5. COMBO BOX

Properties:

Name, Font, Forecolor, Font, Items, Text, Visible, etc Events

SelectedIndexChanged, SelectValueChanged, Keydown, Keyup, KeyPress, Enter, Leave.

Methods

Hide, Show, Items -> add, addrange, insert, clear, remove, removeat, etc 6. LIST BOX

Properties:

Name, Font, Forecolor, Font, Items, Text, Visible, etc Events

SelectedIndexChanged, SelectValueChanged, Keydown, Keyup, KeyPress, Enter, Leave.

Methods

Hide, Show, focus, ITEMS -> add, addrange, insert, clear, remove, etc 7. CHECK BOX & 8. RADIO BUTTON

Properties

Name, checkalign, checked, checkstate, font, forecolor, text, visible, etc Events

Checkedchange, checkedstatechanged, click, etc Methods

Show, hide, focus, etc 9. MONTH CALENDAR

Properties

Name, AnnuallyBoldedDates, MonthlyBoldedDates, BoldedDates, Backcolor, ForeColor, Font, FirstDayofweek, maxdate, mindate, Showtoday, titlebackcolor, titleforecolor, etc

49

VB.Net…

Page 50: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Events

Datechanged, dateselected, etc Methods

Addboldeddates, hide, show, setdate, focus, etc 10. DATE TIME PICKER

Properties

Name, calenderforecolor, calenderfont, calendarmonthbackground, calendartitlecolor, etc

Events

Valuechanged, etc Methods

Hide, show, focus, VALUE -> addseconds, addminutes, addhour, adddays, addmonths, addyears, isleapyear, etc

11. PICTURE BOX:

Properties

Name, image, errorimage, sizemode, backcolor, backgroundimage, borderstyle, etc

Events

Click, layout Methods

Show,hide,focus, IMAGE -> Fromfile, Save, etc 12. Timer Control: Properties: Name, Enable, Interval (1000 = 1 sec)Events: Tick Methods: Start, Stop

50

VB.Net…

Page 51: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Example:Private Sub Timer1_Tick Label1.Text = DateTime.Now.DateLabel2.Text=DateTime.Now.ToLongTimeString.ToString End Sub Private Sub Button1_Click

Timer1.Start()End Sub Private Sub Button2_Click

Timer1.Stop()End Sub 13. Progress Bar: Property: Name, ForeColor, Maximum, Minimum, value, style, enableEvents: -- Methods: -- Example: Private Sub Timer1_Tick If pgbar.Value < 100 Then pgbar.Value += 10 Else pgbar.Value = 0 End IfEnd Sub Tab Control: Property: TabPages Events: -- Methods: --

51

VB.Net…

Page 52: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16. USER INTERFACE DEMO

Public Class

frm_Student_Info

Dim fees As Integer

Dim name As String = ""

Dim mob As Long

Dim str As String

Dim time As String

Dim q As String

Dim br As String

Dim doe As Date

Dim nq As String

Private Sub

frm_Student_Info_Load(ByVal

sender As System.Object, ByVal

e As System.EventArgs) Handles

MyBase.Load

'ComboBox1.Items.Add("CIDCO")'ComboBox1.Items.Insert(0, "OSMANPURA")

cmbbranch.Items.AddRange(New

Object()

{"Select", "Cidco", "Osmanpura",

"City Chowck"})

cmbbranch.SelectedIndex = 0

lstqualification.Items

.AddRange(New Object()

{"MCA", "Msc", "MCM", "Others"})

End Sub

52

VB.Net…

Page 53: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

'ListBox1.Items.Add("MCA")

'ListBox1.Items.Insert(0, "MSc")

Private Sub

lstqualification_SelectedIn

dexChanged(ByVal sender As

System.Object, ByVal e As

System.EventArgs) Handles

lstqualification.SelectedInd

exChanged

If lstqualification.SelectedIndex

= 3 Then

nq = InputBox

("Enter Your qualification")

End If

End Sub

Private Sub

btnsave_Click(ByVal sender

As System.Object, ByVal e As

System.EventArgs) Handles

btnsave.Click

name = txtname.Text

mob=Convert.ToUInt64(txtmobile.Text)

fees = 0

str = ""

If chkjava.Checked = True Then

fees += 3000

End If

If chkccpp.Checked = True Then

fees += 1000

End If

If chkdba.Checked = True Then

fees += 3000

End If

If chkmsnet.Checked = True Then

fees += 3000

End If

If rdomorning.Checked = True

Then

time = "Morning Batch"

ElseIf rdoafternoon.Checked =

True Then

time = "Afternoon Batch"

ElseIf rdoevening.Checked = True

Then

time = "Evening Batch"

ElseIf rdofasttrack.Checked =

True Then

time = "Fast Track Batch"

End If

br =

cmbbranch.SelectedItem.ToString

q=stqualification.SelectedItem.T

oString

doe = dtpbatch.Value

str &= name + vbCrLf

str &= mob.ToString + vbCrLf

str &= fees.ToString() + vbCrLf

str &= time + vbCrLf

str &= q + vbCrLf

str &= br + vbCrLf

str &= doe.Date + vbCrLf

str &= MonthCalendar1.TodayDate

If

lstqualification.SelectedIndex =

3 Then

str &= nq

End If

MsgBox(str)

End Sub

End Class

53

VB.Net…

Page 54: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

54

VB.Net…

Page 55: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

17. MDI DEMO

Public Class Form1 Dim frm2 As Form2 Private Sub LOGINToolStripMenuItem_Click frm2 = New Form2frm2.MdiParent = Mefrm2.Show() End Sub Private Sub EXITToolStripMenuItem_Click If MsgBox("Do You Wish To Exit", MsgBoxStyle.YesNo) = MsgBoxResult.Yes ThenMe.Close()End If End Sub

55

VB.Net…

Page 56: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Class Public Class Form2 Dim frm3 As Form3 Private Sub Button1_Click frm3 = New Form3 frm3.obj = New global_classfrm3.obj.pro_username = TextBox1.Text frm3.MdiParent = Me.MdiParentfrm3.Show()Me.Close() End SubEnd Class Public Class Form3 Public obj As global_class Private Sub Form3_Load Label1.Text = "Hello " + obj.pro_username + " Welcome to SFK INFOTECH PVt. LTD." End SubEnd Class Public Class global_class Private username As String Public Property pro_username() Get Return Me.username End Get Set(ByVal value) Me.username = value End Set 56

VB.Net…

Page 57: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Property End Class

57

VB.Net…

Page 58: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Dialog Control

Public Class Frm_Dialog_Demo

Private Sub btn_font_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_font.Click If fd.ShowDialog = Windows.Forms.DialogResult.OK Then

rtb.SelectionFont = fd.Font

End If

End Sub

Private Sub btn_Color_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Color.Click If cd.ShowDialog = Windows.Forms.DialogResult.OK Then

rtb.SelectionColor = cd.Color

End If

End Sub

58

VB.Net…

Page 59: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Save.Click If sd.ShowDialog = Windows.Forms.DialogResult.OK Then

rtb.SaveFile(sd.FileName)

End If

End Sub

Private Sub btn_open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_open.Click If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then rtb.LoadFile(ofd.FileName) End IfEnd Sub Private Sub btn_New_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_New.Click rtb.Clear()End Sub Private Sub btn_Close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Close.Click Me.Close()End Sub End Class

Note: 1. Above Control is Rich Texbox and it name property set as ‘rtb’

2. Take FontDialogbox, ColorDialogBox, SaveDialogBox, and OpenDialogbox

Controls

From ToolBox Which is Under the Dialog Tab.

59

VB.Net…

Page 60: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO.NETADO.Net Architecture

INTRODUCTION:

ADO.Net Is Essentially A Collection Of Classes That Expose Methods And Attributes

60

VB.Net…

Connected Model Disconnected Model

Application

ApplicationData ReaderData Set

Data ReaderCommandData Adapter

ConnectionConnection

Database

Page 61: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Used To Manage Communication Between An Application And A Database. An Integral Part Of The .Net Framework, ADO.Net Simplifies Database Programming In Visual Studio .NET. THE STANDARD ADO OBJECTS ARE:

Connection – A Connection, As The Name Implies Wraps The Concept Of A Connection With The Database. We Must Have A ‘Connection’ Before We Can Execute A Command And Read Data From A Database. Command – A Command Represent An Instruction Being Send To The Database In Form Of SQL Statements Such As Select, Insert, Update, Delete Or A Name Of A Stored Procedure. DataReader – The Datareader is like a forwardonly, Readonly Cursor to the records retrieved by the Command’s Select Statement, in the front end.

Imports System.Data.SqlClient

Public Class Frm_DML

Dim con As SqlConnection

Dim cmd As SqlCommand

Dim dr As SqlDataReader

Private Sub

Frm_DML_Load(ByVal sender

As Object, ByVal e As

Private Sub

btninsert_Click(ByVal sender

As Object, ByVal e As

System.EventArgs) Handles

btninsert.Click

cmd = New SqlCommand

cmd.CommandType = CommandType.Text

cmd.CommandText =

“Insert into emp values(@empno,

@ename, @job, @sal)”

61

VB.Net…

Page 62: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

System.EventArgs) Handles

Me.Load

con = New SqlConnection("Data

Source=.\sqlexpress;Initial

Catalog=sfk_db;Integrated

Security=True")

End Sub

Public Sub clear()

txtempno.Clear()

txtname.Clear()

txtjob.Clear()

txtsal.Clear()

txtempno.Focus()

End Sub

cmd.Parameters.AddWithValue

("@empno", txtempno.Text.Trim())

cmd.Parameters.AddWithValue

("@ename", txtname.Text.Trim())

cmd.Parameters.AddWithValue

("@job", txtjob.Text.Trim())

cmd.Parameters.AddWithValue

("@sal", txtsal.Text.Trim())

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

End Sub

Private Sub

btnselect_Click(ByVal sender

As Object, ByVal e As

System.EventArgs) Handles

btnselect.Click

If txtempno.Text.Trim.Length

= 0 Then

MsgBox("Enter a Empno")

Else

cmd = New SqlCommand

cmd.CommandType =

CommandType.Text

cmd.CommandText =

"Select * from emp where empno

= " + txtempno.Text

If con.State =

ConnectionState.Closed Then

con.Open()

End If

cmd.Connection = con

Try

Else

MsgBox("No such Empno Exist")

End If

dr.Close()

Catch ex As Exception

MsgBox(ex.Message)

End Try

con.Close()

End If

End Sub

Private Sub

btndelete_Click(ByVal sender

As Object, ByVal e As

System.EventArgs) Handles

btndelete.Click

cmd = New SqlCommand

cmd.CommandType = CommandType.Text

cmd.CommandText =

62

VB.Net…

Page 63: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

dr = cmd.ExecuteReader

If dr.HasRows = True Then

While (dr.Read)

txtempno.Text = dr(0)

txtname.Text = dr(1)

txtjob.Text = dr(2)

txtsal.Text = dr("sal")

End While

"Delete from emp where empno=" +

txtempno.Text

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

End Sub

63

VB.Net…

Page 64: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btnupdate_Click(ByVal sender As Object, ByVal e

As System.EventArgs) Handles btnupdate.Click

cmd = New SqlCommand

cmd.CommandType = CommandType.Text

cmd.CommandText =

"update emp set ename=@ename, job=@job, sal=@sal where empno=@empno”

cmd.Parameters.AddWithValue

("@empno", txtempno.Text.Trim())

cmd.Parameters.AddWithValue

("@ename", txtname.Text.Trim())

cmd.Parameters.AddWithValue

("@job", txtjob.Text.Trim())

cmd.Parameters.AddWithValue

("@sal", txtsal.Text.Trim())

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

End Sub

64

VB.Net…

Page 65: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO – USING STORED PROCEDURE

Imports System.Data.SqlClient

Public Class Form1

Dim con As SqlConnection

Dim cmd As SqlCommand

Dim dr As SqlDataReader

Private Sub Form1_Load(ByVal

sender As System.Object,

ByVal e As System.EventArgs)

Handles MyBase.Load

con = New SqlConnection("Data

Source=.\sqlexpress;Initial

Catalog=sfk_db;Integrated

Security=True;Pooling=False")

End Sub

Public Sub clear()

txtempno.Clear()

txtname.Clear()

txtjob.Clear()

txtsal.Clear()

txtempno.Focus()

End Sub

Private Sub

btninsert_Click(ByVal sender

As System.Object, ByVal e As

System.EventArgs) Handles

btninsert.Click

cmd = New SqlCommand

cmd.CommandType =

CommandType.StoredProcedure

cmd.CommandText = "InsEmp"

cmd.Parameters.AddWithValue

("@empno", txtempno.Text.Trim())

cmd.Parameters.AddWithValue

("@ename", txtname.Text.Trim())

cmd.Parameters.AddWithValue

("@job", txtjob.Text.Trim())

cmd.Parameters.AddWithValue

("@sal", txtsal.Text.Trim())

If con.State = ConnectionState.Closed

Then

con.Open()

End If

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

65

VB.Net…

Page 66: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub

Private Sub

btnselect_Click(ByVal sender

As System.Object, ByVal e As

System.EventArgs) Handles

btnselect.Click

If txtempno.Text.Trim.Length = 0

Then

MsgBox("Enter a Empno")

Else

cmd = New SqlCommand

cmd.CommandType =

CommandType.StoredProcedure

cmd.CommandText = "GetEmp"

If con.State =

ConnectionState.Closed Then

con.Open()

End If

cmd.Connection = con

cmd.Parameters.AddWithValue

("@empno", txtempno.Text.Trim())

Try

dr = cmd.ExecuteReader

If dr.HasRows = True Then

While (dr.Read)

txtempno.Text = dr(0)

txtname.Text = dr(1)

txtjob.Text = dr(2)

txtsal.Text = dr("sal")

End While

Else

MsgBox("No such Empno Exist",

MsgBoxStyle.Exclamation, "SFK")

End If

dr.Close()

Catch ex As Exception

MsgBox(ex.Message)

End Try

con.Close()

Private Sub

btndelete_Click(ByVal sender

As System.Object, ByVal e As

System.EventArgs) Handles

btndelete.Click

cmd = New SqlCommand

cmd.CommandType =

CommandType.StoredProcedure

cmd.CommandText = "DelEmp"

If con.State =

ConnectionState.Closed Then

con.Open()

End If

cmd.Parameters.AddWithValue

("@empno", txtempno.Text)

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

End Sub

Private Sub

btnupdate_Click(ByVal sender

As System.Object, ByVal e As

System.EventArgs) Handles

btnupdate.Click

cmd = New SqlCommand

cmd.CommandType =

CommandType.StoredProcedure

cmd.CommandText = "UpdEmp"

If con.State =

ConnectionState.Closed Then

con.Open()

End If

66

VB.Net…

Page 67: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End If

End Sub

cmd.Parameters.AddWithValue

("@empno", txtempno.Text.Trim())

cmd.Parameters.AddWithValue

("@ename", txtname.Text.Trim())

cmd.Parameters.AddWithValue

("@job", txtjob.Text.Trim())

cmd.Parameters.AddWithValue

("@sal", txtsal.Text.Trim())

cmd.Connection = con

Try

cmd.ExecuteNonQuery()

Catch ex As Exception

MsgBox(ex.Message)

End Try

clear()

End Sub

End Class

/* Stored Procedures */ CREATE PROCEDURE GetEmp

@empno int

AS

select * from emp where empno=@empno

CREATE PROCEDURE DelEmp

@empno int

AS

delete from emp where empno=@empno

CREATE PROCEDURE InsEmp

@empno int,

@eName varchar(20),

@job varchar(10),

@sal int

AS

insert into

emp(empno,ename,job,sal)

values(@empno,@ename,@job,@sal)

CREATE PROCEDURE UpdEmp

@empno int,

@eName varchar(20),

@job varchar(10),

@sal int

AS

update emp set

ename=@ename,

job=@job,

sal=@sal

where empno=@empno

67

VB.Net…

Page 68: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

68

VB.Net…

Page 69: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO.NET DISCONNECTED MODEL

DataSet:

The Dataset is the Central Component in ADO.Net Disconnected Data Access Architecture.

The ADO.Net Architecture uses Dataset Object for in-memory representation of data

i.e.: A Local Copy of the Data from in Database in the Application (Front End).

Once the Dataset is Populated, Accessing the data in the Dataset does not require

interaction with the database, and changes to data in the dataset have no effect on

the database, until the changes are updated with the Database. Hence, this is called as

ADO.Net Disconnected Model.

A DataSet is Like a Collection of Tables in Front End, as it may contain multiple Tables,

each of which will have a collection of Columns and Rows. A DataSet May Also Contain

Integrity Constraints and Relationships.

DataAdapter:

A DataAdapter is responsible for moving the Data between the Datasource (Database) and

the DataSet (Application / Front End). The DataAdapter incorporates the functionality

required to Retrieve Data, Populate DataSet & Perform Updates of the Database.

Some of the Important Properties of a DataAdapter are SELECTCOMMAND, CONNECT &

Important Methods are FILL, UPDATE.

You Can Populate the DataSet by calling the DataAdapter.Fill() Method, which will

execute the instructions contained in the DataAdapter.SelectCommand Property over the

connections specified by the DataAdapter.Connection Property.

If The Changes Made to the Data in DataSet is to be reflected in the Database, then the

DataAdapter.Update Method may be called.

To Update the Database with the changes made to the DataSet, the DataAdapter by

itself cannot generate the SQL statements required for the Database. To Automatically

Generate the SQL statements, we may use SQLCOMMANDBUILDER.

69

VB.Net…

Page 70: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Imports System.Data.SqlClient

Public Class Form1

Dim con As SqlConnection

Dim da As SqlDataAdapter

Dim ds As DataSet

Dim cmdBldr As SqlCommandBuilder

Dim Dtrow As DataRow

Private Sub Form1_Load(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles MyBase.Load

con = New SqlConnection("Data Source=.\sqlexpress;Initial

Catalog=sfk_db;Integrated Security=True;Pooling=False")

'con.Open()

da = New SqlDataAdapter("Select * From Emp", con)

ds = New DataSet()

da.Fill(ds)

dg.DataSource = ds.Tables(0)

'da.Fill(ds, "emp")

'dg.DataSource = ds.Tables("emp")

70

VB.Net…

Page 71: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub

Private Sub btninsert_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btninsert.Click

'adding a new row to the table(0) in dataset DS.

Dtrow = ds.Tables(0).NewRow()

Dtrow(0) = txtempno.Text

Dtrow(1) = txtname.Text

Dtrow(2) = txtjob.Text

Dtrow(3) = txtsal.Text

‘ adding values to the newly added row of

‘ the table in dataset.

ds.Tables(0).Rows.Add(Dtrow)

clear()

End Sub

Public Sub clear()

txtempno.Clear()

txtname.Clear()

txtjob.Clear()

txtsal.Clear()

txtempno.Focus()

End Sub

Private Sub btnselect_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnselect.Click

‘ Declaring an Array of Datarow to hold all

‘ the Rows of the Table.

Dim dtr() As DataRow

dtr = ds.Tables(0).Select("empno=" + txtempno.Text)

'Fetching one the rows into the textboxs from the dataset

If (dtr.Length = 0) Then

MsgBox("Item Not Found")

Else

Dtrow = dtr(0)

71

VB.Net…

Page 72: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

txtname.Text = Dtrow(1)

txtjob.Text = Dtrow(2)

txtsal.Text = Dtrow(3)

End If

End Sub

Private Sub btnupdate_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnupdate.Click

‘Updating the DataSet with changes made in the textboxes

Dtrow(0) = txtempno.Text

Dtrow(1) = txtname.Text

Dtrow(2) = txtjob.Text

Dtrow(3) = txtsal.Text

clear()

End Sub

Private Sub btndelete_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btndelete.Click

‘Delete the row from the dataset

Dtrow.Delete()

clear()

End Sub

Private Sub Btn_Send_To_DB_Click(ByVal sender As

System.Object, ByVal e As System.EventArgs) Handles

Btn_Send_To_DB.Click

‘Sending the Insert, Update, Delete Changes made

‘to the DataSet to the Database

Try

cmdBldr = New SqlCommandBuilder(da)

da.Update(ds)

Catch ex As Exception

MsgBox(ex.Message)

End Try

End Sub

End Class

72

VB.Net…

Page 73: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Data Binding :

Imports System.Data.SqlClient

Public Class emp_database

Public con As SqlConnection

Public da As SqlDataAdapter

Public dt As DataTable

Public ds As DataSet

Public Sub New()

con = New SqlConnection("Data

Source=.\sqlexpress;AttachDbFilename=D:\Ainna\Project\deccan\deccan

\data\stud_addm.mdf;Integrated Security=True")

con.Open()

da = New SqlDataAdapter("select * from emp", con)

ds = New DataSet()

da.Fill(ds)

dt = ds.Tables(0)

End Sub

End Class

Import system.io

Import system.data.sqlclient

Clss Frm_emp

Dim con as sqlconnection

Dim cmd as sqlcommond

Dim dr as sqldatareader

Dim emp_db as new emp_database

73

VB.Net…

Page 74: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub Frm_stud_photo_Load(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles MyBase.Load

con = New SqlConnection("Data Source=.\sqlexpress;Initial

Catalog=stud_addm;Integrated Security=True")

con.Open()

Try

txtempno.DataBindings.Add("text", emp_db.dt, "empno")

txtename.DataBindings.Add("text", emp_db.dt, "ename")

txtjob.DataBindings.Add("text”,emp_db.dt, "job")

Catch ex As Exception

MsgBox(ex.Message)

End Try

End Sub

Private Sub btn_decrement_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btn_decrement.Click

Me.BindingContext(emp_db.dt).Position -= 1

End Sub

Private Sub btn_increment_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btn_increment.Click

Me.BindingContext(emp_db.dt).Position += 1

End Sub

Private Sub btn_low_record_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btn_low_record.Click

Me.BindingContext(emp_db.dt).Position = 0

End Sub

Private Sub btn_high_record_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btn_high_record.Click

Me.BindingContext(emp_db.dt).Position =

Me.BindingContext(emp_db.dt).Count - 1

End Sub

74

VB.Net…

Page 75: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO_DS_ORCL

Imports System.Data.OracleClient

Public Class ADO_DS_ORCL

Dim ds As DataSet

Dim daemp As OracleDataAdapter

Dim dadept As OracleDataAdapter

Dim cmdbld As OracleCommandBuilder

Dim con As OracleConnection

Dim dtr As DataRow

75

VB.Net…

Page 76: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub ADO_DS_ORCL_Load(ByVal sender As

System.Object, ByVal e As System.EventArgs) Handles

MyBase.Load

con = New OracleConnection("User=scott; password=tiger”)

daemp = New OracleDataAdapter("Select empno,ename,job,sal,deptno from emp",

con)

ds = New DataSet

daemp.Fill(ds, "emp")

dg.DataSource = ds.Tables(0)

‘ Populating the ComboBox for Empno

Dim i As Integer

For i = 0 To ds.Tables(0).Rows.Count - 1

cboEmpno.Items.Add(ds.Tables(0).Rows(i)(0))

Next

‘Declaring a Data Set for Populating ComboBox for Deptno

dadept = New OracleDataAdapter("Select deptno from dept", con)

dadept.Fill(ds, "dept")

For i = 0 To ds.Tables(1).Rows.Count - 1

cbodpt.Items.Add(ds.Tables(1).Rows(i)(0))

Next

End Sub

Private Sub cboEmpno_SelectedIndexChanged(ByVal sender

As System.Object, ByVal e As System.EventArgs) Handles

cboEmpno.SelectedIndexChanged

Dim dtrow() As DataRow

dtrow = ds.Tables(0).Select("empno=" + cboEmpno.Text)

dtr = dtrow(0)

txtname.Text = dtr(1)

txtjob.Text = dtr(2)

txtsal.Text = dtr(3)

cbodpt.SelectedItem = dtr(4)

End Sub

76

VB.Net…

Page 77: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btnselect_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnselect.Click

Dim dtrow() As DataRow

dtrow = ds.Tables(0).Select("empno=" + cboEmpno.Text)

If dtrow.Length = 0 Then

MsgBox("Empno Does Not Exist")

Else

dtr = dtrow(0)

txtname.Text = dtr(1)

txtjob.Text = dtr(2)

txtsal.Text = dtr(3)

cbodpt.SelectedItem = dtr(4)

End If

End Sub

Private Sub dg_CellEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles

dg.CellEnter

Dim dtrow() As DataRow

dtrow = ds.Tables(0).Select("empno=" +

dg(0,e.RowIndex).Value.ToString)

dtr = dtrow(0)

cboEmpno.Text = dtr(0)

txtname.Text = dtr(1)

txtjob.Text = dtr(2)

txtsal.Text = dtr(3)

cbodpt.SelectedItem = dtr(4)

End Sub

Private Sub btninsert_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btninsert.Click

dtr = ds.Tables(0).NewRow()

dtr(0) = cboEmpno.Text

dtr(1) = txtname.Text

dtr(2) = txtjob.Text

dtr(3) = txtsal.Text

dtr(4) = cbodpt.Text

ds.Tables(0).Rows.Add(dtr)

77

VB.Net…

Page 78: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub

Private Sub btnupdate_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btnupdate.Click

dtr(0) = cboEmpno.Text

dtr(1) = txtname.Text

dtr(2) = txtjob.Text

dtr(3) = txtsal.Text

dtr(4) = cbodpt.Text

End Sub

Private Sub btndelete_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btndelete.Click

dtr.Delete()

End Sub

Private Sub Btn_Send_To_DB_Click(ByVal sender As

System.Object, ByVal e As System.EventArgs) Handles

Btn_Send_To_DB.Click

cmdbld = New OracleCommandBuilder(daemp)

daemp.Update(ds.Tables(0))

End Sub

End Class

78

VB.Net…

Page 79: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Image Storing In Database

Imports System.Data.SqlClientImports System.IO Public Class Frm_Image_Demo Dim con As SqlConnection Dim cmd As SqlCommand Dim photo() As Byte Dim dr As SqlDataReader Private Sub Frm_Image_Demo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con = New SqlConnection("Data Source=.;Initial Catalog= Test;Integrated Security=True") con.Open()End Sub Private Sub btn_Imageload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Imageload.Click If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then pbphoto.Load(OFD.FileName)End IfEnd Sub Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click 79

VB.Net…

Page 80: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Try cmd = New SqlCommand cmd.CommandText = "Insert into sphoto values(@sid,@name,@photo)" cmd.Parameters.AddWithValue("@sid", txtsid.Text) cmd.Parameters.AddWithValue("@name", txtsname.Text) photo = File.ReadAllBytes(pbphoto.ImageLocation) ‘ photo = File.ReadAllBytes(OFD.FileName) cmd.Parameters.AddWithValue("@photo", photo) If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con cmd.ExecuteNonQuery() MsgBox("Image Saved...!") Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub btn_Select_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Select.Click Try cmd = New SqlCommand cmd.CommandText = "Select Name,Photo From Sphoto Where sid=@sid" cmd.Parameters.AddWithValue("@sid", txtsid.Text) If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con dr = cmd.ExecuteReader If dr.Read() Then txtsname.Text = dr(0) photo = dr(1) File.WriteAllBytes("Photo.jpg", photo) pbphoto.Load("Photo.jpg") Else MsgBox("No Such Record Exist") End If Catch ex As Exception MsgBox(ex.Message) Finally con.Close() dr.Close()

80

VB.Net…

Page 81: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Try End Sub Private Sub btn_close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_close.Click Me.Close() End Sub Private Sub btn_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_clear.Click txtsid.Clear() txtsname.Clear() pbphoto.Image = Nothing End SubEnd Class

Note: 1. Set the SizeMode Property of Picture Box To Strech Image.

3. For Saving Image In SQL Server Database Take Data Type as Image or Varbinary

Crystal Reports

Crystal Report is a business intelligence application used to design and generate report

from a wide range of data sources. Several other application, such as Microsoft Visual

Studio, bundle an OEM version of Crystal Report as a general purpose reporting tool,

Crystal Reports became the de facto standard report writer when Microsoft Released it

with Visual Studio.

The product was originally created by Crystal Services Inc. as Quick Reports when

they couldn’t find a suitable commercial report writer for their accounting software.

After producing version 1.0 through 3.0, the company was acquired in 1994 by Seagate

Technology. Crystal Services was combined with Holostic Systems to form the Information

Management Group of Seagate Software, which later rebranded as Crystal Decision, and

produced version 4.0 through 9.0. Crsytal Decision was acquired in December 2003 by

Business Objects, which has so far produced version 10, 11(XI) and the current verison 12.

81

VB.Net…

Page 82: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Business Objects was acquired by SAP on OCT 8, 2007.

If we want to add a report under a .Net project open “Add New Item” window & select

Reporting in LHS panel, then select Crystal Report from RHS panel, which adds a Report

file, with an extension .rpt. A report when opened has 5 section in it:

1. Report Header 2. Page Header 3. Details

4. Report Footer 5. Page Footer

Report Header: Content placed under this section gets displayed at top of the report i..e

on top of the first page in report e.g.: Company Name, Address etc.

Page Header: Content placed under this section gets displayed at top of every page in to

which the report extends. e.g.: Column Names, Date, Time etc.

Details: Contents into this section generally comes from the DB; this is the actual

information that has to be presented to clients.

Report Footer: this is same as Report Header but gets displayed at bottom of report e.g.:

Signatures, Date & Place.

Page Footer: this is same as Page Header but gets displayed at bottom of every page into

which the report extends. e.g.: Page No’s

Creating a Report: open a new project of type Windows, name it ReportProject, open

add new item window, select Reporting on LHS, choose Crystal Report on RHS, name

the report as Sample.rpt, choose blank report option, click OK. As the report has to

get its information from DB first we need to configure the report with appropriate

data source using the ‘Field Explorer’ window that getds added along with Report

(Shorcut:Ctrl+Alt+T).

Configuring the Report with DB: Open the field explorer, right click on DB Field

Node, select ‘Database Expert’ list of providers, choose ‘Microsoft OLEDB Provider

for Sql Server’, click next, specify the connection details like server name, user id,

password & DB, click Finish which adds a node under OLEDB(ADO), expand the nodes

below: ‘CSharp’, ‘dbo’, ‘Tables’, double click on the table we want to consume, e.g.:

Customer, adds table under selected tables list, click ok, adds selected table under DB

fields node of Field Explorer.

82

VB.Net…

Page 83: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Designing the Report: go into Report Header Section right click in it and select Insert Text

Object that adds an object like a Label, enter content in it & do required alignment using

the format toolbar on top.

- Goto Page Header section right click on it & Select Insert -> Special Field ->

DataDate, place it on LHS of the section, right click on it select format object and

choose the format in which we want to display the date, in the same way select

DataTime & place it on RHS.

- Now open Field Explorer and expand the table Customer we have selected, that

displays the list of columns below, drag and drop each column on to details section

as per your design which will create 1 field on the Page Header (Column Name)

and 1 Field on the Details(Data).

- Now go to Report Footer & Provider the option for users to enter Date, Place and

Signature using the Text Objects and Insert Line Options.

- Now go the Page Footer section right click Insert -> Special Field -> select Page

Number and place it on the Center of the section.

Launching the Report: to display a report we need to use the control

CrystalReportViewer that has to be placed on Form which will be default use Dock

property as Fill. If we want to show a report under the control first it has to be loaded

into the app from its physical location.

Place a CrystalReportViewer control on form and write the following code:

Under Form Load: crystalReportViewer1.ReportSource=<path of report>;

Note: To get path of your report goto Solution Explorer, right click on crystal report

file & select properties, copy value under FullPath property and use it.

83

VB.Net…

Page 84: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

84

VB.Net…

Page 85: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Imports CrystalDecisions.CrystalReports.Engine

Public Class Frm_Report_Demo

Dim rptpath As String

Dim rptdoc As ReportDocument

Private Sub Frm_Report_Demo_Load(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles MyBase.Load

rptdoc = New ReportDocument

rptpath = "D:\Akbar\Report_Demo\Report_Demo\Rpt_EmpDetail.rpt"

rptdoc.Load(rptpath)

CV1.ReportSource = rptdoc

End Sub

Private Sub btn_close_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles btn_close.Click

Me.Close()

End Sub

End Class

85

VB.Net…

Page 86: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

86

VB.Net…

Imports CrystalDecisions.CrystalReports.Engine

Imports CrystalDecisions.SharedPublic Class cry_rpt

Dim rptpath As String

Dim rptdoc As ReportDocument

Private Sub btn_show_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles btn_show.Click

rptdoc = New ReportDocument

rptpath = "D:\crystal_demo\crystal_demo\addm_report.rpt"

rptdoc.Load(rptpath)

CV.ReportSource = rptdoc

Dim PFDs As ParameterFieldDefinitions

Dim PFD As ParameterFieldDefinition

Dim PValues As New ParameterValues

Dim PDis_Value As New ParameterDiscreteValue

PFDs_Value.Value = TextBox1.Text

PFDs = rptdoc.DataDefinition.ParameterFields()

PFD = PFDs.Item("class")

PValues = PFD.CurrentValues

PValues.Clear()

PValues.Add(PDis_Value)

PFD.ApplyCurrentValues(PValues)

CV.ReportSource = rptdoc

CV.Refresh()

End Sub

End Class

Page 87: VBdotnet Introduction

www.sfkinfotech.com Sarfaraz Khan - 9763987372

87

VB.Net…