Professional Documents
Culture Documents
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.
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
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
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
Class Dog
Private Age as integer
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
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.
// C#
abstract class WashingMachine
{
public WashingMachine()
{
// Code to initialize the class goes here.
}
An assembly includes:
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:
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
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
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
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
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
Common Dialogs
OpenFileDialog
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
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
nwindConn.Open()
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");
nwindConn.Open();
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
nwindConn.Open()
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");
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
nwindConn.Open()
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");
nwindConn.Open();
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
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;");
oraConn.Open();
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 .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:
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
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.
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"
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
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)
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
Finally
connection.Close()
End Try
End Sub
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
Try
Directory.CreateDirectory(TextBox1.Text)
'Directory.CreateDirectory("c:\examples")
Catch
End Try
MsgBox("Done")
End Sub