1 / 38

VB Classes

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.

Download Presentation

VB Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. VB Classes ISYS 512

  2. 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

  3. Anatomy of a Class Module Class Module Exposed Part Hidden Part Public Variables & Property Procedures Private Variables Public Procedures & Functions Private Procedures & Functions • Private variables and procedures can be created for internal use. • Encapsulation

  4. 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

  5. Using a Class • Define a class variable using New • Example: Dim MyEmp As New Emp

  6. 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.

  7. 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

  8. 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

  9. 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.

  10. 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.

  11. 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.

  12. 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

  13. 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.

  14. 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

  15. Inheritance Example Public 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

  16. Database Handling Classes ADO.Net Objects Database Classes Data Source Forms Reports

  17. 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.

  18. 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

  19. 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

  20. 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

  21. 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

  22. Modeling 1:M Relation with Classes • Employee • EID • Ename • Dependents • Department • DID • Dname • Employees • Customer • CID • Cname • Orders

  23. 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.

  24. 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.

  25. 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

  26. 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

  27. Implementing a 1:M Relationship With ArrayList Class Customer Public cid As String Public cname As String Public city As String Public rating As String Public orders As New ArrayList Methods: GetData GetOrders Class Order Public OID As String Public Odate As Date Public SalesPerson As String

  28. Customer Class Public 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

  29. GetOrders Method Public 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

  30. Order Class Public 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 Property End Class

  31. 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.

  32. Example

  33. 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

  34. 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

  35. 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

  36. 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

  37. Code Using Assembly Imports MyClassDemo Public 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

  38. 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

More Related