You are on page 1of 37

Namespace

In VB.NET, classes and other data structures for a specific purpose


are grouped together to form a namespaceYou can use the classes in a
namespace, by simply importing the namespace. The Imports keyword is
used to import a namespace to your project. .NET framework provides a
rich set of built in classes, grouped together to various namespaces.
In this lesson, we are using the System namespace. Import the System
namespace (already available in .NET).
Namespace Animals

Classs
Simply speaking, a Class is a definition of a real life object. For
example, Human is a class for representing all human beings. Dog is a
class to represent all Dogs. Classes can contain functions too.
Animals is a namespace.

Public class test


----------veriable
----------Method
----------Properties
----------Events
End class

Object-An object is an instance of a Class. For example, Jimmy is an


object of type Dog. We will create an object in the next section.
Modules-A Module is a group of functions. Unlike functions in
classes, Public functions in modules can be called directly from
anywhere else. VB provides Functions and Subroutines. Functions and
Subroutines are almost the same, but the difference is that a
subroutine can't return a value
Sub Main()

dim obj as new test()


obj.display()

End Sub

Fields
public rooms as integer

Properties
class myclass
private x as integer
Public property x() as Integer
Get
Return x
End Get
Set(ByVal Value As Integer)
x=Value
End Set
End Property
End class

Procedure
Public sub Area()
......................
End Sub

Events
Public class ClassWithEvent
Public Envent ReportProgress(ByVal PercentDone As Integer)
Public Sub DoSomething()
Dim x as integer,y as integer
For x=0 to 10
RaiseEvent ReportProgress(x *10)
For y=0 to 50000
Application.DoEvent()
Next
Next
End Class
Responding to the Event
Public WithEvents obj as ClassWithEvent
obj =new ClassWithEvent
How To Handle Event
Potected Sub Obj_ReportProgress(ByVal PercentDone As Integer) Handles
obj.ReportProgress
textbox1.text=PercentDone
End Sub
OR
Private Sub Form1_Click (ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Click
bj = New ClassWithEvent()
obj.DoSomething()
End Sub

Shared Function
The shared members in a class (both functions and
variables) can be used without creating objects of a class
as shown. The Shared modifier indicates that the method
does not operate on a specific instance of a type and may
be invoked directly from a type rather than through a
particular instance of a type.
Namespace Animals
Class dog
Public shared Function bark()
console.writeline(“Dog is barking”)
End Sub
Public Function walk()
console.writeline(“Dog Is Walking”)
End Sub
End class
End Namespce

Public Module ModMain()


Sub Main()
Anamils.dog.bark()
dim tomi as Animals.dog
tomi=new Animals.Dog()
tomi.walk()
End Sub
End Module
Overloading
Overloading is a simple technique, to enable a single function name
to accept parameters of different type.
Class Addr
Overloads Public Sub Add(A as Integer,B as Integer)
console.writeline(“Adding Integer” + Convert.ToString(a+b))
End Sub
Overloads Public Sub Add(A as String,B as String)
Console.writeline(“Adding String:” + A+B)
End Sub
End Class

Shared Sub Main()


dim ObjAddr as Addr
ObjAddr=new Addr
ObjAddr.Add(10,20)
ObjAddr.Add(“Hello”,”How Are You”)
End Sub

Inheritance
Inheritance is the property in which, a derived class acquires the
attributes of its base class. In simple terms, you can create or
'inherit' your own class (derived class), using an existing class
(base class). You can use the Inherits keyword for this

Class Human
Public Sub Walk()
console.writeline(“Walking”)
End Sub
End Class
Class Programmer
Inherits Human

Public Sub StealCode()


console.writeline(“Stealing Code”)
End Sub
End Class

Sub Main()
dim tom as Programmer
tom=new Progeammer
tom.walk()
tom. StealCode()
End Sub

Overriding
By default, a derived class Inherits methods from its base class. If
an inherited property or method needs to behave differently in the
derived class it can be overridden; that is, you can define a new
implementation of the method in the derived class. The Overridable
keyword is used to mark a function as overridable. The keyword
Overrides is used to mark that a function is overriding some base
class function.

Class Human
Overridable Public Sub Speak()
console.writeline(“Speaking”)
End Sub
End Class

Class Indian
Inherits Human
Overrides Public sub Speak()
console.writeline(“Hindi Speaking”)
End Sub
End Class

Class MainClass
Sub Main()
Dim Tom as Indian
Tom=new Indian
Tom.Speak()
End Sub
End Class
Polymorphism
Polymorphism is the property in which a single object can take more
than one form. For example, if you have a base class named Human, an
object of Human type can be used to hold an object of any of its
derived type. When you call a function in your object, the system
will automatically determine the type of the object to call the
appropriate function. For example, let us assume that you have a
function named speak() in your base class. You derived a child class
from your base class and overloaded the function speak(). Then, you
create a child class object and assign it to a base class variable.
Now, if you call the speak() function using the base class variable,
the speak() function defined in your child class will work. On the
contrary, if you are assigning an object of the base class to the
base class variable, then the speak() function in the base class will
work. This is achieved through runtime type identification of
objects. See the example.

This example is exactly the same as the one we saw in the previous
lesson. The only difference is in the Shared Sub Main() in the class
MainClass

Class MainClass
Shared Sub Main()
Dim Tom as Indian
Tom=new Indian
Tom.Speak()
End Sub
End Class

Constructors & Destructors


A Constructor is a special function which is called automatically
when a class is created. In VB.NET, you should use useNew() to create
constructors. Constructors can be overloaded (see Lesson 4), but
unlike the functions, the Overloads keyword is not required. A
Destructor is a special function which is called automatically when a
class is destroyed. In VB.NET, you should use useFinalize() routine
to create Destructors. They are similar to Class_Initialize and
Class_Terminate in VB 6.0.

Class Dog
Private Age as integer

Public Sub New(val as Integer)


Console.Writeline ("Dog is Created With Age " +
Convert.ToString(val))
Age=val
End Sub
Overrides Protected Sub Finalize()
Console.Writeline ("Dog is Destroyed")
End Sub

Shared Sub Main()


Dim Jimmy, Jacky as Dog
'Create the objects
'This will call the default constructor
Jimmy=new Dog
'This will call the parameterized constructor
Jacky=new Dog(10)
End Sub
'The Destruction will be done automatically, when
'the program ends. This is done by the Garbage
'Collector.
End Class

Interfaces
Interfaces allow us to create definitions for component interaction.
They also provide another way of implementing polymorphism. Through
interfaces, we specify methods that a component must implement
without actually specifying how the method is implemented. We just
specify the methods in an interface and leave it to the class to
implement those methods. Visual Basic .NET does not support multiple
inheritance directly but using interfaces we can achieve multiple
inheritance. We use the Interface keyword to create an interface and
implements keyword to implement the interface

Sub Main()
Dim OneObj As New One()
Dim TwoObj As New Two()
'creating objects of class One and Two
OneObj.disp()
OneObj.multiply()
TwoObj.disp()
TwoObj.multiply()
'accessing the methods from classes as specified in the interface
End Sub

OUTPUT-
Hi From One
146.01
Hi From Two
643.4
End Module

Public Interface test()


sub disp()
Function Multiple() as Double

End Interface
Public class one
Implements Test
Public i as double=12
Public j as double=12.17
sub disp()Implements Test.disp
console.writeline(“Hi From One”)
End Sub
Public function Multiple()as double Implements Test.Multiple
writeLine(i*j)
read()
End Sub
End Class
Public class Two
Implements Test
Public i as double=20
Public j as double=32.17
sub disp()Implements Test.disp
console.writeline(“Hi From Two”)
End Sub
Public function Multiple()as double Implements Test.Multiple
writeLine(i*j)
read()
End Sub
End Class

Abstract Classes
Abstract classes are closely related to interfaces. They are classes
that cannot be instantiated, and are frequently either partially
implemented, or not at all implemented. One key difference between
abstract classes and interfaces is that a class may implement an
unlimited number of interfaces, but may inherit from only one
abstract (or any other kind of) class. A class that is derived from
an abstract class may still implement interfaces. Abstract classes
are useful when creating components because they allow you specify an
invariant level of functionality in some methods, but leave the
implementation of other methods until a specific implementation of
that class is needed. They also version well, because if additional
functionality is needed in derived classes, it can be added to the
base class without breaking code.

An abstract class is denoted in Visual Basic by the keyword


MustInherit. In C#, the abstract modifier is used. Any methods that
are meant to be invariant may be coded into the base class, but any
methods that are to be implemented are marked in Visual Basic with
the MustOverride modifier. In C#, the methods are marked abstract.
The following example shows an abstract class:

' Visual Basic


Public MustInherit Class WashingMachine
Sub New()
' Code to instantiate the class goes here.
End sub
Public MustOverride Sub Wash
Public MustOverride Sub Rinse (loadSize as Integer)
Public MustOverride Function Spin (speed as Integer) as Long
End Class

// C#
abstract class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes here.
}

abstract public void Wash();


abstract public void Rinse(int loadSize);
abstract public long Spin(int speed);
}

' Visual Basic


Public Class MyWashingMachine
Inherits WashingMachine
Public Overrides Sub Wash()
' Wash code goes here
End Sub
Public Overrides Sub Rinse (loadSize as Integer)
' Rinse code goes here
End Sub
Public Overrides Function Spin (speed as Integer) as Long
' Spin code goes here
End Sub
End Class
// C#
class MyWashingMachine : WashingMachine
{
public MyWashingMachine()
{
// Initialization code goes here.
}

override public void Wash()


{
// Wash code goes here.
}

override public void Rinse(int loadSize)


{
// Rinse code goes here.
}

override public long Spin(int speed)


{
// Spin code goes here.
}
}
What is the exact defination of "Object"?
An object is an instance of a Class
What is the size of .NET object?
Default size when a class gets loaded in memory is 8 bytes
Difference between VB dll and assemblies in .NET ?
Assemblies can contain DLL and EXE both. Different versions
of one DLL can be handeled by assemblies. They overcome the
DLL Hell problem. Assemblies Contain Manifest and MetaData
files. These are the seprate files that describes the
Assembly and its attributes.

VB DLL is inprocess.DLL run with an exe


where as DLL are not self executable.
we can reuse DLLs .DLL are not platform independent
If we have more then one Versions of a DLL we can face DLL
Hell Problem.

What is the Difference between Overriding and overloading?


OverLoading : All the method will share the same name but
it differes based on the parameter, type of parameter and
number of parameter

Overriding : The method in the derived class the has the


same name in the base class and it changes the behaviour or
functionality of the method in the base class.
What is an abstract class?
It is a class which contains at least one abstract method
(A method without any implementation). Other methods can
have implementations. This class can not be instantiated.
It can always become a base class for other classes.

In order to get assembly info whcih namespace we should import?


system.reflection

Trace and Debug belongs to which namespaces?


system.process.diagnostics

What is the Common Language Runtime?


The Common Language Runtime (CLR) is the virtual machine component of
Microsoft's .NET initiative. It is Microsoft's implementation of the
Common Language Infrastructure (CLI) standard, which defines an
execution environment for program code. The CLR runs a form of
bytecode called the Common Intermediate Language (CIL).

Developers using the CLR write code in a language such as C# or


VB.Net. At compile-time, a .NET compiler converts such code into MSIL
(Microsoft Intermediate Language) code

What are the different types of assemblies available ?


Private,Public,Shared and Satellite
How many classes can a single .NET DLL contain?
Many

What is a satellite Assembly?


An assembly containing localized resources for another assembly

Will VB supports mutiple inheritace?


No

which class is used to run the exe application file in vb.net


Process

What is finalise method and what are the role of it?


Release object memory

What is the difference between a class module and a code module?


Class modules are instantiated at runtime to create objects and code
modules do not have instances.
VB Language
Namespaces
A namespace is a collection of different classes
Assemblies
An assembly is the building block of a .NET application. It is a self
describing collection of code, resources, and metadata (data about
data, example, name, size, version of a file is metadata about that
file). An Assembly is a complied and versioned collection of code and
metadata that forms an atomic functional unit. Assemblies take the
form of a dynamic link library (.dll) file or executable program
file (.exe) but they differ as they contain the information found in
a type library and the information about everything else needed to
use an application or component. All .NET programs are constructed
from these Assemblies. Assemblies are made of two parts: manifest,
contains information about what is contained within the assembly and
modules, internal files of IL code which are ready to run. When
programming, we don't directly deal with assemblies as the CLR and
the .NET framework takes care of that behind the scenes. The assembly
file is visible in the Solution Explorer window of the project.

An assembly includes:

Information for each public class or type used in the assembly –


information includes class or type names, the classes from which an
individual class is derived, etc

Information on all public methods in each class, like, the method


name and return values (if any)

Information on every public parameter for each method like the


parameter's name and type

Information on public enumerations including names and values

Information on the assembly version (each assembly has a specific


version number)

Intermediate language code to execute

A list of types exposed by the assembly and list of other assemblies


required by the assembly
Data Types in VB .NET

Data Type Size in BytesDescription Type


Byte 1 8-bit unsigned integer System.Byte
Char 2 16-bit Unicode characters System.Char
Integer 4 32-bit signed integer System.Int32
Double 8 64-bit floating point variable System.Double
Long 8 64-bit signed integer System.Int64
Short 2 16-bit signed integer System.Int16
Single 4 32-bit floating point variable System.Single
String Varies Non-Numeric Type System.String
Date 8 System.Date
Boolean 2 Non-Numeric Type System.Boolean
Object 4 Non-Numeric Type System.Object
Decimal 16 128-bit floating point variable System.Decimal

Access Specifiers
Access specifiers let's us specify how a variable, method or a class
can be used. The following are the most commonly used one's:

Public: Gives variable public access which means that there is no


restriction on their accessibility
Private: Gives variable private access which means that they are
accessible only within their declaration content
Protected: Protected access gives a variable accessibility within
their own class or a class derived from that class
Friend: Gives variable friend access which means that they are
accessible within the program that contains their declaration
Protected Friend: Gives a variable both protected and friend access
Static: Makes a variable static which means that the variable will
hold the value even the procedure in which they are declared ends
Shared: Declares a variable that can be shared across many instances
and which is not associated with a specific instance of a class or
structure
ReadOnly: Makes a variable only to be read and cannot be written

Explicit Conversions Function


CBool - use this function to convert to Bool data type
CByte - use this function to convert to Byte data type
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CObj - use this function to convert to Object type
CShort - use this function to convert to Short data type
CSng - use this function to convert to Single data type
CString - use this function to convert to String data type

Enumeration
Enumeration is a related set of constants. They are used when working
with many constants of the same type. It's declared with the Enum
keyword.

Imports System.Console
Module Module1

Enum Seasons
Summer = 1
Winter = 2
Spring = 3
Autumn = 4
End Enum

Sub Main()
Write("Summer is the" & Seasons.Summer & "season")
End Sub

End Module

Window Control
Button
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
'You place the code here to perform action when Button is clicked
End Sub

TextBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Welcome to TextBoxes"
End Sub
Code to Validate User Input
Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub
Creating a TextBox in Code
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
Dim TextBox1 as New TextBox()
TextBox1.Text="Hello Mate"
TextBox1.Location=New Point(100,50)
TextBox1.Size=New Size(75,23)
Me.Controls.Add(TextBox1)
End Sub
End Class

RichTextBox
Code for creating bold and italic text in a RichTextBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's
'return property to SelectionStart which selects the text to format
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
'creating a new font object to set the font style
RichTextBox1.SelectionFont = ifont
'assigning the value selected from the RichTextBox the font style
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
Dim bfont As New Font(RichTextBox1.Font, FontStyle.Bold)
RichTextBox1.SelectionFont = bfont
End Sub

Code for Setting the Color of Text


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's return
'property to SelectionStart which selects the text
RichTextBox1.SelectionColor = Color.Blue
'setting the color for the selected text with SelectionColor property
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
RichTextBox1.SelectionColor = Color.Yellow
End Sub

Code for Saving Files to RTF


Private Sub Save_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Save.Click
RichTextBox1.SaveFile("hello.rtf")
'using SaveFile method to save text in a rich text box to hard disk
End Sub
Private Sub Load_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Load.Click
RichTextBox2.LoadFile("hello.rtf")
'using LoadFile method to read the saved file
End Sub

Label
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs)_
Handles MyBase.Load Dim Label1 As New Label()
Label1.Text = "Label"
Label1.Location = New Point(135, 70)
Label1.Size = New Size(30, 30)
Me.Controls.Add(Label1)
End Sub

LinkLabel

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object,


ByVal_
e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.startvbdotnet.com")
'using the start method of system.diagnostics.process class
'process class gives access to local and remote processes
End Sub

CheckBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
TextBox1.Text = "Checked"
Else
TextBox1.Text = "UnChecked"
End If
End Sub

RadioButton
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
TextBox1.Text = "Selected"
Else
TextBox1.Text = "Not Selected"
End If
End Sub

ListBox
Code to display the index of an item
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedIndex
'using the selected index property of the list box to select the
index
End Sub
Counting the number of Items in a ListBox
TextBox1.Text = ListBox1.Items.Count

Code to display the item selected from ListBox in a TextBox


TextBox1.Text = ListBox1.SelectedItem

Code to remove a particular item


ListBox1.Items.RemoveAt(4)

Code to Remove all items


ListBox1.Items.Clear()

ComboBox
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
'selecting the item from the ComboBox with selected item property
End Sub

TreeView
Public Class Form12 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "

#End Region

Private Sub TreeView1_AfterSelect(ByVal sender As System.Object,


ByVal e As_
System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
Label1.Text = "You are here->" & " " & e.Node.FullPath
'displaying the path of the selected node
Label2.Text = "Current node selected:" & " " & e.Node.Text
'displaying the selected node
End Sub
End Class

CheckedListBox
Panel, GroupBox, PictureBox
PictureBox
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = Image.FromFile("C:\sample.gif")
'loading the image into the picturebox using the FromFile method of
the image class
'assuming a GIF image named sample in C: drive
End Sub

ToolTip, ErrorProvider
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Do not leave this blank")
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_


As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
ErrorProvider1.SetError(TextBox1, "Cannot leave textbox blank")
Else
ErrorProvider1.SetError(TextBox1, "")
End If
End Sub

Common Dialogs
OpenFileDialog

Private FileName As String


Dim sr As StreamReader
With OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
sr = New StreamReader(FileName)
RichTextBox1.Text = sr.ReadToEnd()

End If
End With

SaveFileDialog
Dim sw As StreamWriter
With SaveFileDialog1
.FileName = FileName
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
sw = New StreamWriter(FileName)
sw.Write(RichTextBox1.Text)
End If
End With

FontDialog
With FontDialog1
.Font = RichTextBox1.Font
.Color = RichTextBox1.ForeColor
If .ShowDialog = DialogResult.OK Then
setFont()
End If
End With

Private Sub setFont()


Try
With FontDialog1
RichTextBox1.Font = .Font
If .ShowColor Then
RichTextBox1.ForeColor = .Color
'setting the color
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Color Dialog
With ColorDialog1
.Color = RichTextBox1.ForeColor
.CustomColors = CustomColors
If .ShowDialog() = DialogResult.OK Then
RichTextBox1.ForeColor = .Color
CustomColors = .CustomColors
End If
ColorDialog1.Reset()
End With
ADO.NET

Sample Code
sqlClient
[Visual Basic]
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualBasic

Public Class Sample


Public Shared Sub Main()
Dim nwindConn As SqlConnection = New SqlConnection("Data
Source=localhost;" & _
"Integrated Security=SSPI;Initial Catalog=northwind")

Dim catCMD As SqlCommand = nwindConn.CreateCommand()


catCMD.CommandText = "SELECT CategoryID, CategoryName FROM
Categories"

nwindConn.Open()

Dim myReader As SqlDataReader = catCMD.ExecuteReader()

Do While myReader.Read()
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}",
myReader.GetInt32(0), myReader.GetString(1))
Loop

myReader.Close()
nwindConn.Close()
End Sub
End Class

[C#]
using System;
using System.Data;
using System.Data.SqlClient;

class Sample
{
public static void Main()
{
SqlConnection nwindConn = new SqlConnection("Data
Source=localhost;Integrated Security=SSPI;Initial
Catalog=northwind");

SqlCommand catCMD = nwindConn.CreateCommand();


catCMD.CommandText = "SELECT CategoryID, CategoryName FROM
Categories";

nwindConn.Open();

SqlDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

OleDb
[Visual Basic]
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports Microsoft.VisualBasic

Public Class Sample

Public Shared Sub Main()


Dim nwindConn As OleDbConnection = New
OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;" & _
"Integrate
d Security=SSPI;Initial Catalog=northwind")

Dim catCMD As OleDbCommand = nwindConn.CreateCommand()


catCMD.CommandText = "SELECT CategoryID, CategoryName FROM
Categories"

nwindConn.Open()

Dim myReader As OleDbDataReader = catCMD.ExecuteReader()

Do While myReader.Read()
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}",
myReader.GetInt32(0), myReader.GetString(1))
Loop

myReader.Close()
nwindConn.Close()
End Sub
End Class

[C#]
using System;
using System.Data;
using System.Data.OleDb;

class Sample
{
public static void Main()
{
OleDbConnection nwindConn = new
OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated
Security=SSPI;Initial Catalog=northwind");

OleDbCommand catCMD = nwindConn.CreateCommand();


catCMD.CommandText = "SELECT CategoryID, CategoryName FROM
Categories";

nwindConn.Open();
OleDbDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

Odbc
[Visual Basic]
Imports System
Imports System.Data
Imports System.Data.Odbc
Imports Microsoft.VisualBasic

Public Class Sample

Public Shared Sub Main()


Dim nwindConn As OdbcConnection = New OdbcConnection("Driver={SQL
Server};Server=localhost;" & _
"Trusted_Con
nection=yes;Database=northwind")

Dim catCMD As OdbcCommand = new OdbcCommand("SELECT CategoryID,


CategoryName FROM Categories", nwindConn)

nwindConn.Open()

Dim myReader As OdbcDataReader = catCMD.ExecuteReader()

Do While myReader.Read()
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}",
myReader.GetInt32(0), myReader.GetString(1))
Loop

myReader.Close()
nwindConn.Close()
End Sub
End Class
[C#]
using System;
using System.Data;
using System.Data.Odbc;

class Sample
{
public static void Main()
{
OdbcConnection nwindConn = new OdbcConnection("Driver={SQL
Server};Server=localhost;" +
"Trusted_Connection
=yes;Database=northwind");

OdbcCommand catCMD = new OdbcCommand("SELECT CategoryID,


CategoryName FROM Categories", nwindConn);

nwindConn.Open();

OdbcDataReader myReader = catCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
myReader.GetString(1));
}

myReader.Close();
nwindConn.Close();
}
}

OracleClient
[Visual Basic] Copy Code
Imports System
Imports System.Data
Imports System.Data.OracleClient
Imports Microsoft.VisualBasic

Class Sample

Public Shared Sub Main()

Dim oraConn As OracleConnection = New OracleConnection("Data


Source=MyOracleServer;Integrated Security=yes;")

Dim oraCMD As OracleCommand = New OracleCommand("SELECT


CUSTOMER_ID, NAME FROM DEMO.CUSTOMER", oraConn)

oraConn.Open()
Dim myReader As OracleDataReader = oraCMD.ExecuteReader()

Do While (myReader.Read())
Console.WriteLine(vbTab & "{0}" & vbTab & "{1}",
myReader.GetInt32(0), myReader.GetString(1))
Loop

myReader.Close()
oraConn.Close()
End Sub
End Class
[C#]
using System;
using System.Data;
using System.Data.OracleClient;

class Sample
{
public static void Main()
{
OracleConnection oraConn = new OracleConnection("Data
Source=MyOracleServer;Integrated Security=yes;");

OracleCommand oraCMD = new OracleCommand("SELECT CUSTOMER_ID,


NAME FROM DEMO.CUSTOMER", oraConn);

oraConn.Open();

OracleDataReader myReader = oraCMD.ExecuteReader();

while (myReader.Read())
{
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),
myReader.GetString(1));
}

myReader.Close();
oraConn.Close();
}
}
ADO.NET is a set of classes that expose data access services to
the .NET programmer. ADO.NET provides a rich set of components for
creating distributed, data-sharing applications. It is an integral
part of the .NET Framework, providing access to relational data, XML,
and application data. ADO.NET supports a variety of development
needs, including the creation of front-end database clients and
middle-tier business objects used by applications, tools, languages,
or Internet browsers

The ADO.NET Data Architecture


Data Access in ADO.NET relies on two components: DataSet and Data
Provider.
DataSet -The dataset is a disconnected, in-memory representation of
data. It can be considered as a local copy of the relevant portions
of the database.
Data Provider- The Data Provider is responsible for providing and
maintaining the connection to the database. A DataProvider is a set
of related components that work together to provide data in an
efficient and performance driven manner.

The .NET Framework currently comes with two DataProviders: the SQL
Data Provider which is designed only to work with Microsoft's SQL
Server 7.0 or later and the OleDb DataProvider which allows us to
connect to other types of databases like Access and Oracle. Each
DataProvider consists of the following component classes:

Connection object:- Which provides a connection to the database


Command object :-Which is used to execute a command
DataReader object:-Which provides a forward-only, read only,
connected recordset
DataAdapter object:-Which populates a disconnected DataSet with data
and performs update

The Connection Object


The Connection object creates the connection to the database.
Microsoft Visual Studio .NET provides two types of Connection
classes: the SqlConnection object, which is designed specifically to
connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection
object, which can provide connections to a wide range of database
types like Microsoft Access and Oracle. The Connection object
contains all of the information required to open a connection to the
database.
The Command Object
The Command object is represented by two corresponding classes:
SqlCommand and OleDbCommand. Command objects are used to execute
commands to a database across a data connection. The Command objects
can be used to execute stored procedures on the database, SQL
commands, or return complete tables directly. Command objects provide
three methods that are used to execute commands on the database:

ExecuteNonQuery: Executes commands that have no return values such as


INSERT, UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object


The DataReader object provides a forward-only, read-only, connected
stream recordset from a database. Unlike other components of the Data
Provider, DataReader objects cannot be directly instantiated. Rather,
the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a
SqlDataReader object, and the OleDbCommand.ExecuteReader method
returns an OleDbDataReader object. The DataReader can provide rows of
data directly to application logic when you do not need to keep the
data cached in memory. Because only one row is in memory at a time,
the DataReader provides the lowest overhead in terms of system
performance but requires the exclusive use of an open Connection
object for the lifetime of the DataReader.

The DataAdapter Object


The DataAdapter is the class at the core of ADO .NET's disconnected
data access. It is essentially the middleman facilitating all
communication between the database and a DataSet. The DataAdapter is
used either to fill a DataTable or DataSet with data from the
database with it's Fill method. After the memory-resident data has
been manipulated, the DataAdapter can commit the changes to the
database by calling the Update method. The DataAdapter provides four
properties that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied
back to the database and the appropriate InsertCommand,
DeleteCommand, or UpdateCommand is executed.
Example
Code to Retrieve Data using Select Command
Imports System.Data.SqlClient
Public Class Form1 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()

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


System.EventArgs)Handles MyBase.Load
myConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
Try
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader()
While dr.Read()
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
End Sub
End Class

Retrieving records with a Console Application


Imports System.Data.SqlClient
Imports System.Console
Module Module1
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As SqlDataReader

Sub Main()
Try
myConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader
Do
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
End While
Loop While dr.NextResult()
Catch
End Try
dr.Close()
myConnection.Close()
End Sub
End Module

Inserting Records
Imports System.Data.SqlClient
Public Class Form2 Inherits System.Windows.Forms.Form
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra as Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
myConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Insert into Jobs values 12,'IT Manager',
100,300,_
myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myConnection.Close()
End Sub
End Class

Deleting a Record
myCommand = New SqlCommand("Delete from Authors where
city='Oakland'",_
myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("Records affected" & ra)
myConnection.Close()

Updating Records
myConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Update Authors Set city='Oakland' where
city=_
'San Jose' ",myConnection)
ra=myCommand.ExecuteNonQuery()
MessageBox.Show("Records affected" & ra)
myConnection.Close()

MsAccess Database
Code for retrieving records

Imports System.Data.OleDb
Public Class Form1 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e as _
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_
Data Source=C:\emp.mdb;")
cn.Open()
cmd = New OleDbCommand("select * from table1", cn)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr(0)
TextBox2.Text = dr(1)
TextBox3.Text = dr(2)
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Class

Why Datareader is useful?


Datareader is read only or forward only.So it is very fast
to fetch the data from database.

Which are namespaces for ADO.NET?


namespaces for ADO.NET is System.Data
Can you give a overview of ADO.NET architecture ?
Data Access in ADO.NET relies on two components: DataSet and Data
Provider.
DataSet -The dataset is a disconnected, in-memory representation of
data. It can be considered as a local copy of the relevant portions
of the database.The data in DataSet can be loaded from any valid data
source like Microsoft SQL server database, an Oracle database or from
a Microsoft Access database.
Data Provider -The Data Provider is responsible for providing and
maintaining the connection to the database

Each DataProvider consists of the following component classes:

The Connection object which provides a connection to the database


The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only,
connected recordset
The DataAdapter object which populates a disconnected DataSet with
data and performs update

What are the two fundamental objects in ADO.NET ?


The Connection object which provides a connection to the database
The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only,
connected recordset
The DataAdapter object which populates a disconnected DataSet with
data and performs update

What is difference between dataset and datareader ?


Nature of Connection:
Dataset: is generally used to employ disconnected architecture of
Ado.Net
DataReader: is directly connected to database system.

Local Storage:
Dataset: It reads data from database and stores in local system.
DataReader: No Local storage is required.

Where to use:
Dataset: If you are going more number of operations(updates, inserts
and deletes) on database and updates done in batch wise, then dataset
will be best option. Use Dataset, if you are going to implement
sites, which are no need of changes on every client clicks, such as
"Carting in shoping mall sites", "display information in websites
from database".
DataReader: If you are going to fewer operations and directly
implementation of queires on database, the datareader is best option.
Use DataReader, if you are going to implement "Booking a berth in
Railways", "display current price in Stock Market".
Performance: Choose Dataset or DataReader According to situation,
purpose and uses of database display.

How do we use stored procedure in ADO.NET?

Writing a stored procedure


Insert recore
CREATE PROCEDURE dbo.InsertCustomer
(
@CustomerID nchar(5),
@CompanyName nvarchar(40),
@ContactName nvarchar(30),
@ContactTitle nvarchar(30),
@Address nvarchar(60),
@City nvarchar(15),
@Region nvarchar(15),
@PostalCode nvarchar(10),
@Country nvarchar(15),
@Phone nvarchar(24),
@Fax nvarchar(24)
)
AS
INSERT INTO Customers
(
CustomerID,
CompanyName,
ContactName,
ContactTitle,
Address,
City,
Region,
PostalCode,
Country,
Phone,
Fax
)
VALUES
(
@CustomerID,
@CompanyName,
@ContactName,
@ContactTitle,
@Address,
@City,
@Region,
@PostalCode,
@Country,
@Phone,
@Fax
)

Select record
CREATE PROCEDURE dbo.SelectCustomer
(
@CustomerID nchar(5)
)
AS
SET NOCOUNT ON
SELECT
CustomerID,
CompanyName,
ContactName,
ContactTitle,
Address,
City,
Region,
PostalCode,
Country,
Phone,
Fax
FROM Customers NOLOCK
WHERE CustomerID = @CustomerID

Delete Record
CREATE PROCEDURE dbo.DeleteCustomer
(
@CustomerID nchar(5)
)
AS
DELETE FROM Customers
WHERE CustomerID = @CustomerID
RETURN @@ROWCOUNT

Creating a Connection
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" + _
"Initial Catalog=Northwind;Data Source=PTK800"

Dim connection As SqlConnection = New SqlConnection(connectionString)


connection.Open()
Try
Console.WriteLine(connection.State.ToString())
Finally
connection.Close()
End Try

Insert records
Public Sub InsertCustomer()
Dim connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
Try
Dim command As SqlCommand = _
New SqlCommand("InsertCustomer", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@CustomerID", "PAULK")
command.Parameters.Add("@CompanyName", "Pauly's Bar")
command.Parameters.Add("@ContactName", "Paul Kimmel")
command.Parameters.Add("@ContactTitle", "The Fat Man")
command.Parameters.Add("@Address", "31025 La Jolla")
command.Parameters.Add("@City", "Inglewood")
command.Parameters.Add("@Region", "CA")
command.Parameters.Add("@Country", "USA")
command.Parameters.Add("@PostalCode", "90425")
command.Parameters.Add("@Phone", "(415) 555-1234")
command.Parameters.Add("@Fax", "(415) 555-1235")
Console.WriteLine("Rows inserted: " + _
command.ExecuteNonQuery().ToString)
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
Finally
connection.Close()
End Try
End Sub

Select record
Public Sub SelectCustomer()
Dim connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
Try

Dim command As SqlCommand = _


New SqlCommand("SelectCustomer", _ connection)
command.Parameters.Add("@CustomerID", "PAULK")
command.CommandType = CommandType.StoredProcedure

Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)


Dim table As DataTable = New DataTable
adapter.Fill(table)

Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
Finally
connection.Close()
End Try
End Sub

Delete record
Public Sub DeleteCustomer(Optional ByVal commandID As String = _
"PAULK")
Dim connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
Try
Dim command As SqlCommand = _
New SqlCommand("DeleteCustomer", connection)
command.CommandType = CommandType.StoredProcedure

command.Parameters.Add("@CustomerID", commandID)

Console.WriteLine("Rows deleted: " + _


command.ExecuteNonQuery().ToString())

Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
Finally
connection.Close()
End Try
End Sub

Code to create a file and read from it

File Handling
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal....., Byval.....)Handles
Button1.Click
Dim fs as New FileStream("file.doc", FileMode.Create,
FileAccess.Write)
Dim s as new StreamWriter(fs)
s.WriteLine("This is an example of using file handling concepts in VB
.NET.")
s.WriteLine("This concept is interesting.")
s.Close()

fs=New FileStream("file.doc",FileMode.Open,FileAccess.Read)
Dim d as new StreamReader(fs)
d.BaseStream.Seek(0,SeekOrigin.Begin)
'Seek method is used to move the cursor to different positions in a
file, in this code, to
'the beginning
while d.peek()>-1
'peek method of StreamReader object tells how much more data is left
in the file
RichTextbox1.Text &= d.readLine()
End while
d.close()
End Sub

Code to work with File and Directory Class


Imports System.IO

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click

Try
Directory.CreateDirectory(TextBox1.Text)
'Directory.CreateDirectory("c:\examples")
Catch
End Try
MsgBox("Done")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _


System.EventArgs) Handles Button2.Click
Try
If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then
File.Copy(OpenFileDialog1.FileName, TextBox1.Text & "\" & _
OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndex
Of("\")))
'The above line of code uses OpenFileDialog control to open a dialog
box where you
'can select a file to copy into the newly created directory
End If
Catch
End Try
MsgBox("File Copied Successfully")
End Sub
End Class

You might also like