VB.NET Classes ISYS 546. Classes A class is program structure that defines a user-defined data type...

37
VB .NET Classes ISYS 546
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of VB.NET Classes ISYS 546. Classes A class is program structure that defines a user-defined data type...

VB .NET Classes

ISYS 546

Classes

• A class is program structure that defines a user-defined data type that are used to create objects.

• An instance of a class is called an object. • Abstraction is the process to create a model

of an object, for the purpose of determining the characteristics (properties) and behaviors (methods) of the object.

Advantages of Object-Oriented Programming

• Reusable objects– A class can be used in multiple projects.– New classes can be created by inheritance.

• Building-block concept

Adding a Class to a Project

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

• Steps:– Adding properties

• Declare Public variables in the General Declaration section

• Property procedures: Set / Get

– Adding methods

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

Anatomy of a Class Module

Class Module

Public Variables & Property Procedures

Public Procedures & Functions

Exposed Part

Private Variables

Private Procedures & Functions

Hidden Part

Class ExamplePublic Eid As StringPublic Ename As StringPublic salary As DoublePublic Function tax() As Doubletax = salary * 0.1End Function

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.

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

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.

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.

Implementing a Write-Only Property

• Declare the property procedure as WriteOnly with only the Set block.

• Ex. Create a Password property:Private hiddenPassword as StringPublic WriteOnly Property Password() As String Set(ByVal Value As String) hiddenPassword=Value End Set End Property

• How to create a write-once property?

Modeling 1:M Relation with Classes

• Object-Oriented systems allow multi-value attribute.

• Employee– EID– Ename– Dependents

• Department– DID– Dname– Employees

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.

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.

ArrayList Demo

Dim testArrayList As New ArrayList()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

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)

testArrayList.Add(Fruits)

testArrayList.Add(f2)

TextBox1.Text = testArrayList.Item(0)

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

TextBox3.Text = testArrayList.Item(2)(1)

TextBox4.Text = testArrayList.Item(3).Age

End Sub

For Each Loop with ArrayList

Dim testArrayList As New ArrayList()

Dim f2 As New DataForm2()

Dim Fruits() As String = {"Apple", "orange", "Banana"}

testArrayList.Add("David")

testArrayList.Add(20)

testArrayList.Add(Fruits)

testArrayList.Add(f2)

Dim myObj As Object

For Each myObj In testArrayList

MessageBox.Show(myObj.GetType.ToString)

Next

Implementing a 1:M Relationship With ArrayList

Public did As StringPublic dname As StringPublic emps As New arrayList ()

Public eid As StringPublic ename As StringPublic salary As Double

Class Department

Class Employee

To Add a New EmpDim department As New Dept()Private Sub DeptForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load department.did = "D1" department.dname = "MIS" TextBox1.Text = department.did TextBox2.Text = department.dnameEnd SubPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim newemp As New Emp() With newemp .Eid = TextBox3.Text .Ename = TextBox4.Text .salary = Val(TextBox5.Text) End With TextBox3.Text = vbNullString TextBox4.Text = vbNullString TextBox5.Text = vbNullString department.emps.Add(newemp)End Sub

To Find Total Salary and Number of Employees

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

Dim temp As Emp

Dim totalsal As Double

totalsal = 0

For Each temp In department.emps

totalsal = totalsal + temp.salary

Next temp

TextBox7.Text = totalsal.ToString

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

TextBox6.Text = department.emps.Count.ToString

End Sub

Database Access with 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.

Single-Record-Handling Class ExampleImports 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()

Get

RecExist = hiddenexist

End Get

End Property

Public Sub getData(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.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 MsgBox("Record does not exist") ‘Better let user’s program to display msg Else hiddenexist = True cid = objDataReader("cid") CName = objDataReader("CName") City = objDataReader("City") Rating = objDataReader("Rating") End If objConn.Close() End Sub

Public Sub SaveNew()

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb"

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

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

Classes That Create Oledb Objects

• Example: Create a class that uses methods to return DataReader.

Imports System.Data.OleDbPublic Class ReaderServer Public Function CustReader() As OleDbDataReader Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() CustReader = objComm.ExecuteReader() End Function

Public Function OrderReader() As OleDbDataReader Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from orders;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() OrderReader = objComm.ExecuteReader() End FunctionEnd Class

Using the ClassDim cReader As New ReaderServer()

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

Dim reader As OleDb.OleDbDataReader

reader = cReader.CustReader()

Do While reader.Read() = True

ListBox1.Items.Add(reader("cid"))

Loop

End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

Dim reader As OleDb.OleDbDataReader

reader = cReader.OrderReader

Dim strResult As String

Do While reader.Read() = True

If reader("cid") = ListBox1.SelectedItem Then

strResult = strResult + reader("oid") + " " + reader("odate") + vbCrLf

End If

Loop

TextBox1.Text = strResult

End Sub

Importing Data From Database to Class

• Example: Customer/Order class:• Public Class CustOrders

– Public cid As String– Public CName As String– Public City As String– Public Rating As String– Public orders As New arrayList()– Public Sub getData(ByVal SearchID As String)

• Public Class Order– Public OID As String– Public Odate As Date– Public SalesPerson As String– End Class

• Demo: VBClass/CustOrdForm.vb

Public Sub getOrders(ByVal SearchID As String)

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.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.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

• Use the CustReader class to create a CID listbox.

• Use the GetData method to initialize the CustOrd object.

• Use the GetOrder method to retrieve customer’s orders and add to the Orders collection of the CustOrd object.

Creating Listbox

Dim custOrd As New CustOrders()

Dim cReader As New ReaderServer()

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

Dim reader As OleDb.OleDbDataReader

reader = cReader.CustReader()

Do While reader.Read() = True

ListBox1.Items.Add(reader("cid"))

Loop

End Sub

Initializing CustOrd Object

custOrd.getData(ListBox1.SelectedItem) TextBox1.Text = custOrd.City TextBox2.Text = custOrd.CName custOrd.getOrders(ListBox1.SelectedItem) Dim strResult As String Dim ordItem As Order For Each ordItem In custOrd.orders

strResult = strResult + ordItem.OID + " " + ordItem.Odate + " " + ordItem.SalesPerson + vbCrLf Next TextBox3.Text = strResult TextBox4.Text = custOrd.orders.Count.ToString

Assemblies

• An assembly is a logical grouping of functionality into a physical file. One or many business logic components can be reside in an assembly.

• This collection of components is compiled into a .DLL file.

• We can import this .DLL component to any VB projects.

Steps to Create An Assembly

• Create a class library with classes.– You can also use existing classes by Project/Add

Existing Item

• Select Build/Build Solution to compile the code.– When the class library is compiled successfully, an

assembly is created and stored in the project’s Bin folder.

• Note: A ClassLibrary project does not reference System.Windows.Forms namespace.

Using the Assembly

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

• Import the assembly.

Code Using Assembly

Imports MyAssembly

Public Class UseAssembly

Inherits System.Windows.Forms.Form

Dim testAssembly As New MyAssembly.Customer()

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

testAssembly.cid = "1"

testAssembly.getData(testAssembly.cid)

TextBox1.Text = testAssembly.CName

TextBox2.Text = testAssembly.Rating

End Sub

End Class