VB Classes

38
VB Classes ISYS 512

description

VB Classes. ISYS 512. Adding a Class to a Project. Project/Add C lass *** MyClass is a VB keyword. Steps: Adding properties Declare Public variables in the General Declaration section Property procedures: Set / Get Adding methods Adding events, exceptions. Anatomy of a Class Module. - PowerPoint PPT Presentation

Transcript of VB Classes

Page 1: VB Classes

VB Classes

ISYS 512

Page 2: VB Classes

Adding a Class to a Project

• Project/Add Class– *** MyClass is a VB keyword.

• Steps:– Adding properties

• Declare Public variables in the General Declaration section

• Property procedures: Set / Get

– Adding methods– Adding events, exceptions

Page 3: VB Classes

Anatomy of a Class Module

Class Module

Public Variables & Property Procedures

Public Procedures & Functions

Exposed Part

Private Variables

Private Procedures & Functions

Hidden Part

•Private variables and procedures can be created for internal use.•Encapsulation

Page 4: VB Classes

Class Code Example

Public Eid As String

Public Ename As String

Public salary As Double

Public Function tax() As Double

tax = salary * 0.1

End Function

Page 5: VB Classes

Using a Class

• Define a class variable using New– Example: Dim MyEmp As New Emp

Page 6: VB Classes

Creating Property with Property Procedures

• Implementing a property with a public variable the property value cannot be validated by the class.

• We can create read-only, write-only, or write-once properties with property procedure.

• Steps:– Declaring a private class variable to hold the property

value.

– Writing a property procedure to provide the interface to the property value.

Page 7: VB Classes

Private pvEid As String Private pvEname As String Private pvSalary As Double Public Property eid() As String Get eid = pvEid End Get Set(ByVal Value As String) pvEid = Value End Set End Property Public Property eName() As String Get eName = pvEname End Get Set(ByVal Value As String) pvEname = Value End Set End Property Public Property Salary() As Double Get Salary = pvSalary End Get Set(ByVal Value As Double) pvSalary = Value End Set End Property

Page 8: VB Classes

Property Procedure Code Example

Public Class Emp2 Public SSN As String Public Ename As String Public DateHired As Date Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value < 1 Or Value > 4 Then hiddenJobCode = 1 Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get End Property

End Class

Page 9: VB Classes

How the Property Procedure Works?

• When the program sets the property, the property procedure is called and the code between the Set and End Set statements is executed. The value assigned to the property is passed in the Value argument and is assigned to the hidden private variable.

• When the program reads the property, the property procedure is called and the code between the Get and End Get statements is executed.

Page 10: VB Classes

Implementing a Read-Only Property

• Declare the property procedure as ReadOnly with only the Get block.

• Ex. Create a YearsEmployed property from the DateHired property:

Public ReadOnly Property YearsEmployed() As Long Get YearsEmployed = Now.Year - DateHired.Year End Get End Property

– Note: It is similar to a calculated field in database.

Page 11: VB Classes

Overloading

A class may have more than one methods with the same name but a different argument list (with a different number of parameters or with parameters of different data type), different parameter signature.

Page 12: VB Classes

Method Overloading Using the Overloads Keyword

Public Overloads Function tax() As Double

tax = salary * 0.1

End Function

Public Overloads Function tax(ByVal sal As Double) As Double

tax = sal * 0.1

End Function

Page 13: VB Classes

Inheritance

• The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.

Page 14: VB Classes

Employee Super Class with Three SubClasses

All employee subtypes will have emp nbr, name, address, and date-hired

Each employee subtype will also have its own attributes

Page 15: VB Classes

Inheritance ExamplePublic Class Emp

Public Eid As String

Public Ename As String

Public salary As Double

Public Function tax() As Double

tax = salary * 0.1

End Function

End Class

Public Class secretary

Inherits Emp

Public WordsPerMinute As Integer

End Class

Page 16: VB Classes

Database Handling Classes

Data SourceADO.NetObjects

DatabaseClasses

FormsReports

Page 17: VB Classes

Single-Record-Handling Classes

– Retrieves a single record from the database and makes it available to your application in the form of an object.

– The fields in the record are exposed as the object’s properties.

– Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.

Page 18: VB Classes

Single-Record-Handling Class Example

Imports System.Data.OleDb

Public Class Customer

Public cid As String

Public CName As String

Public City As String

Public Rating As String

Private hiddenexist As Boolean

Private cn As OleDb.OleDbConnection

Public ReadOnly Property RecExist() As Boolean

Get

RecExist = hiddenexist

End Get

End Property

Page 19: VB Classes

Public Sub getData(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb"

Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read() = False Then hiddenexist = False Else hiddenexist = True cid = objDataReader("cid") CName = objDataReader("CName") City = objDataReader("City") Rating = objDataReader("Rating") End If objConn.Close() End Sub

Page 20: VB Classes

Public Sub SaveNew()

Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb"

Dim objConn As New OleDbConnection(strConn)

objConn.Open()

Dim strSQLInsert As String

strSQLInsert = "Insert into Customer values ('"

strSQLInsert = strSQLInsert & cid & "','" & CName & "','"

strSQLInsert = strSQLInsert & City & "','" & Rating & "')"

Dim objCommInsert As New OleDbCommand(strSQLInsert, objConn)

objCommInsert.ExecuteNonQuery()

objConn.Close()

End Sub

Page 21: VB Classes

Using the SaveNew Method to Add A New Customer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim newCust As New Customer()

newCust.cid = TextBox1.Text

newCust.CName = TextBox2.Text

newCust.City = TextBox3.Text

newCust.Rating = TextBox4.Text

newCust.SaveNew()

TextBox1.Text = ""

TextBox2.Text = ""

TextBox3.Text = ""

TextBox4.Text = ""

End Sub

Page 22: VB Classes

Modeling 1:M Relation with Classes

• Employee– EID– Ename– Dependents

• Department– DID– Dname– Employees

• Customer– CID– Cname– Orders

Page 23: VB Classes

ArrayList

• ArrayList is a data structure used to store a set of values.– Its capacity is automatically expanded as

needed.– Values stored in an arraylist do not have to be

the same data type.– Flexibility when inserting/deleting elements.

Page 24: VB Classes

ArrayList Properties & Methods

• Define an arraylist:– Dim myArrayList As New ArrayList()

• Properties:Count, Item, etc.– myArrayList.Item(0) 0-based index

• Methods:– Clear, Add, Insert, Remove, RemoveAt,

Contains, IndexOf, etc.

Page 25: VB Classes

ArrayList Demo

Dim testArrayList As New ArrayList()

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

Dim f2 As New Form2()

testArrayList.Add("David")

testArrayList.Add(20)

TextBox1.Text = testArrayList.Item(0)

TextBox2.Text = testArrayList.Item(1).ToString

End Sub

Page 26: VB Classes

For Each Loop with ArrayList

Dim testArrayList As New ArrayList()

testArrayList.Add("David")

testArrayList.Add(20)

testArrayList.Add(Fruits)

Dim myObj As Object

For Each myObj In testArrayList

MessageBox.Show(myObj.GetType.ToString)

Next

Page 27: VB Classes

Implementing a 1:M Relationship With ArrayList

Public cid As String Public cname As String Public city As String Public rating As String Public orders As New ArrayListMethods:

GetDataGetOrders

Public OID As StringPublic Odate As DatePublic SalesPerson As String

Class Customer

Class Order

Page 28: VB Classes

Customer ClassPublic Class Customer Public cid As String Public cname As String Public city As String Public rating As String Public orders As New ArrayList Private hiddenexist As Boolean Public Sub getData(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read() = False Then hiddenexist = False MessageBox.Show("Record does not exist") Else hiddenexist = True cid = objDataReader("cid") cname = objDataReader("CName") city = objDataReader("City") rating = objDataReader("Rating") End If objConn.Close() End Sub

Page 29: VB Classes

GetOrders MethodPublic Sub getOrders(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from orders where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True Dim ord As New Order() ord.oid = objDataReader("oid") ord.CID = objDataReader("cid") ord.Odate = objDataReader("odate") ord.SalesPerson = objDataReader("salesPerson") orders.Add(ord) Loop If orders.Count = 0 Then MessageBox.Show("customer has no order") End If objConn.Close() End Sub

Page 30: VB Classes

Order ClassPublic Class Order Private pvOID As String Private pvCID As String Private pvOdate As Date Private pvSalesPerson As String Public Property OID() As String Get oid = pvOID End Get Set(ByVal value As String) pvOID = value End Set End Property Public Property CID() As String Get CID = pvCID End Get Set(ByVal value As String) pvCID = value End Set End Property Public Property Odate() As Date Get Odate = pvOdate End Get Set(ByVal value As Date) pvOdate = value End Set End Property Public Property Salesperson() As String Get Salesperson = pvSalesPerson End Get Set(ByVal value As String) pvSalesPerson = value End Set End PropertyEnd Class

Page 31: VB Classes

Binding Datagrid to an ArrayList

• DataGridView1.DataSource = myCustomer.orders

• Members of the arraylist are instances of same class.

• The properties of the class are defined by property procedure.

Page 32: VB Classes

Example

Page 33: VB Classes

Code Example Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cid from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cid")) Loop objConn.Close() End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Dim myCustomer As New Customer myCustomer.getData(ListBox1.SelectedItem) TextBox1.Text = myCustomer.cname TextBox2.Text = myCustomer.rating myCustomer.getOrders(myCustomer.cid) DataGridView1.DataSource = myCustomer.orders End Sub

Page 34: VB Classes

Difference between Assembly and Class

• A class defined in a project is available to that project only.

• Once a class is compiled in an assembly it can be used by any projects.

• To create an assembly:– Start a Class Library project

Page 35: VB Classes

Steps to Create An Assembly• Start a Class Library project• Create classes

– You can also use existing classes defined in other projects by Project/Add Existing Item

• Save project• Select Build/Build to compile the code.

– When the class library is compiled successfully, an assembly is created and stored in the project’s Bin/Release folder.

– Example: A testClassLib project is created in C:\VS2008Examples, then the assembly is found in:

– C:\VS2008Examples\testClassLib\testClassLib\bin\Release

Page 36: VB Classes

Using the Assembly

• Reference the assembly: Project/Add Reference and use the Browse button to select the assembly.

• Import the assembly.– Global import:

• Project property windows/References

– Local import• Using the Imports statement

Page 37: VB Classes

Code Using Assembly

Imports MyClassDemoPublic Class Form1 Dim myButton As New Button Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim myCls As New DemoCls1 MessageBox.Show(myCls.myName) End Sub

Page 38: VB Classes

Changes to Assembly

• Old projects referencing the assembly will get the latest version of the assembly.

• Compatible changes:– Changes to assembly that will not break the older projects. – Examples:

• Adding a property, adding a method

• Incompatible changes– Changes to assembly that will break the older projects. – Examples:

• Deleting or renaming a property or a method