Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.

Slides:



Advertisements
Similar presentations
1 VBScript Session What we learn last session?
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to XHTML Programming the World Wide Web Fourth edition.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 6- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Classes, Exceptions, Collections, and Scrollable Controls
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Chapter 6, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 6 Sub Procedures And Functions.
Chapter 14 Inheritance. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Inheritance Basics Derived classes, with.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 2- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Lists, Loops, Validation, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 The Basics of Javascript Programming the World Wide Web Fourth.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 JavaScript and XHTML Documents Programming the World Wide Web Fourth.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 Cascading Style Sheets Programming the World Wide Web Fourth edition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET Programming the World Wide Web Fourth.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Security Panel Application Introducing.
Introduction to Visual Basic.NET Uploaded By: M.Sheraz anjum.
Copyright © 2014 Pearson Education, Inc. Chapter 12 Classes, Collections, and Inheritance.
Chapter 12 OOP: Creating Object- Oriented Programs Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Chapter 11 Component-Level Design
Chapter 13 – Introduction to Classes
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 14: More About Classes.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Benchmark Series Microsoft Excel 2013 Level 2
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Chapter 11: Classes and Objects
Chapter 7: Sub and Function Procedures
12-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
OOP-Creating Object-Oriented Programs
Excel and VBA Creating an Excel Application
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Creating Object Oriented Programs Object oriented (OO) terminology Class vs. object Instantiate an object in a project Understand Class_Initialize / Terminate.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
CSI 101 Elements of Computing Spring 2009 Lecture # 14 – Classes and Objects Wednesday, April 15th, 2009 and Monday, April 20th, 2009.
Instructor: Adil Ibrahim Office: 212 Ullrich Phone: ibrahima 1.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2005: Reloaded Second Edition
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Chapter 6 OOP: Creating Object-Oriented Programs Programming In Visual Basic.NET.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 12 Classes, Collections and Scrollable Controls Topics Classes Abstract Data Types Objects, Properties, Methods Exceptions Collections Object Browser.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Programming with Microsoft Visual Basic th Edition
Week Classes Introduction Classes Abstract Data Types Objects, Properties, Methods.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 12 Classes, Collections, and.
Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 An Introduction to Classes, Objects, and object-oriented development.
Programming Logic and Design Seventh Edition
Object-Oriented Programming: Classes and Objects
Object-Oriented Programming: Classes and Objects
VISUAL BASIC.
Classes, Collections, and Inheritance
Programming with Microsoft Visual Basic 2008 Fourth Edition
Object-Oriented Programming: Classes and Objects
CIS16 Application Development and Programming using Visual Basic.net
STARTING OUT WITH Visual Basic 2008
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Classes, Exceptions, Collections, and Scrollable Controls 12

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Introduction Classes Abstract Data Types Objects, Properties, Methods Exceptions Collections Object Browser Scrollable Controls

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Classes and Objects 12.1 Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Abstract Data Types An abstract data type (ADT) is a data type created by a programmer ADTs are important in computer science and object-oriented programming An abstraction is a model of something that includes only its general characteristics Dog is an abstraction Defines a general type of animal but not a specific breed, color, or size A dog is like a data type A specific dog is an instance of the data type

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Classes A class is a program structure that defines an abstract data type Must create the class first Then can create instances of the class Class instances share common attributes VB forms and controls are classes Each control in the toolbox represents a class Placing a button on a form creates an instance, or object, of the class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Properties, Methods, & Events Programs communicate with an object using the properties and methods of the class Class properties example: Buttons have Location, Text, and Name properties Class methods example: The Focus method functions identically for every single button Class event procedures: Each button in a form has a different click event procedure

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object Oriented Design The challenge is to design classes that effectively cooperate and communicate Analyze application requirements to determine ADTs that best implement the specifications Classes are fundamental building blocks Typically represent nouns of some type A well-designed class may outlive the application Other uses for the class may be found

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object Oriented Design Example Specifications: We need to keep a list of students that lets us track the courses they have completed. Each student has a transcript that contains all information about his or her completed courses. At the end of each semester, we will calculate the grade point average of each student. At times, users will search for a particular course taken by a student. Nouns from the specification above typically become classes in the program design Verbs such as calculate GPA and search become methods of those classes

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide OOD Class Characteristics ClassAttributes (properties)Operations (methods) StudentLastName, FirstName, Display, Input IdNumber StudentListAllStudents, CountAdd, Remove, FindStudent CourseSemester, Name, Display, Input Grade,Credits TranscriptCourseList, CountDisplay, Search, CalcGradeAvg

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Interface and Implementation Class interface is the portion of the class visible to the application programmer Made available by creating properties, methods, and events that are public Class implementation is the portion of the class hidden from client programs Kept hidden by designating member variables, properties, & methods as private Hiding of data and procedures inside a class is referred to as encapsulation

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating a Class 12.2 To Create a Class in Visual Basic, You Create a Class Declaration The Class Declaration Specifies the Member Variables, Properties, Methods, and Events That Belong to the Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Declaration Student is the name of the class Examples of MemberDeclarations are presented in the following slides To create a new class: Click Add New Item button on toolbar Select Class from Add New Item dialog box Provide a name for the class and click Add Adds a new, empty class file (.vb) to project Public Class Student MemberDeclarations End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Member Variables A variable declared inside a class declaration Syntax: AccessSpecifier may be Public or Private Example: AccessSpecifer VariableName As DataType Public Class Student Public strLastName As String Holds last name Public strFirstName As String Holds first name Public strId As String Holds ID number End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Creating an Instance of a Class A two step process creates an instance of a class Declare a variable whose type is the class Create instance of the class with New keyword and assign the instance to the variable freshman defined here as an object variable Can accomplish both steps in one statement Dim freshman As New Student() freshman = New Student() Dim freshman As Student

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Accessing Members Can work with Public member variables of a class object in code using this syntax: For example: If freshman references a Student class object And Student class has public member variables strFirstName, strLastName, and strID Can store values in member variables with freshman.strFirstName = "Joy" freshman.strLastName = "Robinson" freshman.strId = "23G794" objectVariable.memberVariable

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Property Procedure A property procedure is a function that defines a property Controls access to property values Procedure has two sections: Get and Set Get code executes when value is retrieved Set code executes when value is stored Properties almost always declared Public to allow access from outside the class Set code often provides data validation logic

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Property Procedure Syntax Public Property PropertyName() As DataType Get Statements End Get Set(ParameterDeclaration) Statements End Set End Property

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Property Procedure Example Public Class Student ' Member variables Private sngTestAvg As Single Public Property TestAverage() As Single Get Return sngTestAvg End Get Set(ByVal value As Single) If value >= 0.0 And value <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set End Property End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Setting and Validating a Property TestAverage property is set as shown: Passes 82.3 into value parameter of Set If in the range 0.0 to 100.0, value is stored If outside the range, message box displayed instead of value being stored Set(ByVal value As Single) If value >= 0.0 And value <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set Dim freshman as New Student() freshman.TestAverage = 82.3

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Read-Only Properties Useful at times to make a property read-only Allows access to property values but cannot change these values from outside the class Add ReadOnly keyword after access specifier This causes the propertyName to be read-only -- not settable from outside of the class Public ReadOnly Property PropertyName() As DataType Get Statements End Get End Property

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Read-Only Property Example ' TestGrade property procedure ReadOnly Property TestGrade() As Char Get If sngTestAverage >= 90 return "Ac Else If sngTestAverage >= 80 return "Bc Else If sngTestAverage >= 70 return "Cc Else If sngTestAverage >= 60 return "Dc Else return "Fc End If End Get End Property

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object Removal & Garbage Collection Memory space is consumed when objects are instantiated Objects no longer needed should be removed Set object variable to Nothing so it no longer references the object Object is a candidate for garbage collection when it is no longer referenced by any object variable The garbage collector monitors for and automatically destroys objects no longer needed freshman = Nothing

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Going Out of Scope An object variable instantiated within a procedure is local to that procedure An object goes out of scope when Referenced only by local variables and The procedure ends Object removed once it goes out of scope An object instantiated in a procedure and assigned to a global variable is not removed Reference remains when procedure ends

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Going Out of Scope, Example Sub CreateStudent() Dim sophomore As Student sophomore = New Student() sophomore.FirstName = "Travis" sophomore.LastName = "Barnes" sophomore.IdNumber = "17H495" sophomore.TestAverage = 94.7 g_studentVar = sophomore End Sub With this statement, sophomore will not go out of scope. Without this statement, it will go out of scope when the procedure ends. (g_studentVar is a module-level variable.)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Comparing Object Variables Multiple variables can reference the same object Can test if two variables refer to same object Must use the Is operator The = operator cannot be used to test for this Dim collegeStudent As Student Dim transferStudent As Student collegeStudent = New Student() transferStudent = collegeStudent If collegeStudent Is transferStudent Then ' Perform some action End If

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide IsNot & Nothing Object Comparisons Use the IsNot operator to determine that two variables do not reference the same object Use the special value Nothing to determine if a variable has no object reference If collegeStudent IsNot transferStudent Then ' Perform some action End If If collegeStudent Is Nothing Then ' Perform some action End If

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Can create an entire array of object variables Declare an array whose type is a class Instantiate an object for each element Creating an Array of Objects ' Declare the array Dim mathStudents(9) As Student Dim i As Integer For i = 0 To 9 ' Assign each element to an object mathStudents(i) = New Student() Next i

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Can use object variables as arguments to a procedure or function Example: student object s as an argument Pass object variable with the procedure call Objects As Procedure Arguments Sub DisplayStudentGrade(ByVal s As Student) ' Displays a students grade. MessageBox.Show("The grade for " & _ s.FirstName & " " & s.LastName & _ " is " & s.TestGrade.ToString) End Sub DisplayStudentGrade(freshman)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Objects Passed ByVal and ByRef If argument is declared using ByRef Values of object properties may be changed The original object variable may be assigned to a different object If argument is declared using ByVal Values of object properties may be changed The original object variable may not be assigned to a different object

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Functions Can Return Objects Dim freshman As Student = GetStudent() … Function GetStudent() As Student Dim s As New Student() s.FirstName = InputBox("Enter first name.") s.LastName = InputBox("Enter last name.") s.IdNumber = InputBox("Enter ID number.") s.TestAvg = CSng(InputBox("Enter test average.")) Return s End Function Example below instantiates a student object Prompts for and sets its property values Then returns the instantiated object

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Class Methods In addition to properties, a class may also contain Sub procedures and functions Methods are Sub procedures and functions defined in a class Typically operate on data stored in the class The following slide shows a Clear method for the Student class Method called with freshman.Clear() Method clears member data in the Student class object referenced by freshman

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Clear Method for Student Class Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg (...Property procedures omitted...) ' Clear method Public Sub Clear() strFirstName = String.Empty strLastName = String.Empty strId = String.Empty sngTestAvg = 0.0 End Sub End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Constructors A constructor is a method called automatically when an instance of the class is created Think of constructors as initialization routines Useful for initializing member variables or performing other startup operations To create a constructor, simply create a Sub procedure named New within the class Next slide shows a Student class constructor The statement freshman = New Student() Creates an instance of the Student class Executes constructor to initialize properties of the Student object referenced by freshman

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Constructor Example Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg ' Constructor Public Sub New() strFirstName = "(unknown)" strLastName = "(unknown)" strId = "(unknown)" sngTestAvg = 0.0 End Sub (The rest of this class is omitted.) End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Finalizers VB provides a class method named Finalize Called automatically just before garbage collector removes an instance of a class Select Finalize from method name drop-down list to let Visual Basic create the following template Add your code following MyBase.Finalize() Protected Overrides Sub Finalize() MyBase.Finalize() End Sub

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Using the Output Window Usually shown at bottom of Visual Studio display If not appearing, click View, Other Windows, then Output to display A valuable debugging tool Messages about an application displayed here Can add your own messages to Output window using Debug.WriteLine method Causes the expression Output to appear in the Output window Insert following code in form Load event to enable Debug.WriteLine(Output) Debug.Listeners.Add(New ConsoleTraceListener())

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Create a Class Tutorial 12-1 demonstrates code needed to create the Student class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Collections 12.3 A Collection Holds a Group of Items It Automatically Expands and Shrinks in Size to Accommodate the Items Added to It and Allows Items to Be Stored With Associated Key Values, Which May Be Used in Searches

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Collections A collection is similar to an array A single unit that contains several items Can access items in a collection by numeric index A collections indices begin at one, not zero Collections automatically expand and shrink as items are added and removed The items stored in a collection do not have to be of the same type

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide A Collection is a Class New collections are instantiations of the Collection Class The Collection Class provides methods and properties for use with individual collections Dim customers As Collection customers = New Collection() ' Or alternatively Dim customers As New Collection()

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Adding Items to a Collection Add is a method of the Collection class Object is a variable that refers to a collection Item can be an object, variable, or value that is added to the collection Key is a unique value optionally used to identify a member of the collection Before or After optionally specifies where a new item should be placed in the collection Default is to insert at the end of the collection Object.Add(Item [, Key] [, Before] [,After])

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Uses of Before and After Add custData with key "Smith" before the item with key "Thomas Add custData with key "Smith" after the item with key "Reece Add custData after 3 rd item in collection customers.Add(custData, "Smith", "Thomas") customers.Add(custData, "Smith",, "Reece") customers.Add(custData,,,3)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Add Method Exceptions An exception can occur when adding to a collection so Try-Catch should be used Cannot add member with same key as another member of the collection If a key or index is specified for a Before or After, the value must exist Try customers.Add(custData, "Smith") Catch ex as ArgumentException MessageBox.Show(ex.Message) End Try

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Accessing Item by Their Indices Can access an item in a collection using an index value Index value can be used in two ways: Using the collections Item method Item is the default method so it can be omitted Get value at index 3 of names collection by: names.Item(3) –or- names(3) Object(Index) Object.Item(Index)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide IndexOutOfRange Exception If an invalid index is encountered, an index out of range exception will occur Should use Try-Catch to trap such messages Ctype casts collection object to Customer object Try Dim cust as Customer Get collection index from user input Dim index as Integer = CInt(txtIndex.Text) Locate the customer in the collection cust = CType(customers.Item(index), Customer) Catch ex as IndexOutOfRangeException MessageBox.Show(ex.Message) End Try

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide The Count Property The Count property of a collection gives the number of current items in the collection Note that, unlike an array, a collection index is not zero based First item in a collection found at index 1 Following code adds collection items to a list box Dim intX As Integer For intX = 1 To names.Count lstNames.Items.Add(names(intX).ToString()) Next intX

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Searching for an Item by Key Value Item method can be used to retrieve an item with a specific index If Expression is a string, it is used as a key to search for a member with a matching key If Expression is numeric, it is used as an index value for the item If no item is found (via key or index), an exception occurs Object.Item(Expression)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Retrieving Item Examples Find studentCollection item with key If Option Strict on, must cast result to Student Retrieve all members by index and display LastName property in a message box Dim s as Student s = CType(studentCollection.Item(49812), Student) Dim intIndex as Integer Dim s as Student For intIndex = 1 to studentCollection.Count s = Ctype(studentCollection.Item(intIndex), Student) MessageBox.Show(s.LastName) Next intIndex

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Using References Versus Copies When an Item in a collection is a fundamental VB data type, only a copy is retrieved This code does not change the item at index 1 The Item in this collection is an object so: A reference is returned instead of a copy LastName of object in collection is changed Dim s as Student s = CType(studentCollection.Item("49812"), Student) s.LastName = "Griffin" Dim intNum as Integer intNum = CType(numbers(1), Integer) intNum = 0

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide For Each Loop with a Collection Dim s As Student For Each s In studentCollection MessageBox.Show(s.LastName) Next s Can use a For Each loop to read members of a collection Eliminates the counter variable required to use a For…Next Also no need to compare to Count property

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Removing Members of a Collection Remove is a method of the Collection class Object refers to collection Member removed from Expression can be Numeric and interpreted as an index Or a string and interpreted as a key value Exception thrown if Expression not found Object.Remove(Expression)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Removing Member Examples Verify is a key value in collection, then remove member with this key value Verify index location 7 exists in collection, then remove member at this index location If studentCollection.Contains(49812) Then studentCollection.Remove("49812") End If Dim intIndex As Integer = 7 If intIndex > 0 and _ intIndex <= studentCollection.Count Then studentCollection.Remove(intIndex) End If

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Working with Collections Since a collection is an instance of a class Procedures accept collections as arguments Functions can return a collection Follow same guidelines as any class object Parallel collections work like parallel arrays Can use index to relate parallel collections just as we did with arrays Or can use key values to relate collections

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Student Collection Application 12.4 Create an Application that Uses a Collection of Student Objects

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Student Collection Application Forms Slide Select student ID number from list box to see detail information for the student Click Remove Student button remove an instance of the Student class Click Add Student button to create a new instance of the Student class Add Student form

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Object Browser 12.5 The Object Browser Is a Dialog Box That Allows You to Browse All Classes and Components Available to Your Project

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Using the Object Browser A dialog box with information about objects used in a project Allows you to examine Information about forms used in a project Classes created for the project Other components used by VB in the project Tutorial 12-3 uses the Object Browser to examine the Student Collection project

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Object Browser, Example Student class selectedClass members shown

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scroll Bars and Track Bars 12.6 The HScrollBar, VScrollBar, and TrackBar Controls Provide a Graphical Way to Adjust a Number Within a Range of Values

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Visual Appearance and Usage HScrollBar and VScrollBar look like normal scroll bars TrackBar has an arrow pointer as the slider with tick marks Scrollable controls hold integers in their Value property Position of slider corresponds to Value Move scroll bar to increase or decrease Value Right increases, left decreases horizontal bar Up increases, down decreases vertical bar

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Scrollable Control Properties Minimum – the bar s lowest possible value Maximum – the bar's highest possible value Value – the bar's value at the current position LargeChange – change in the Value property with a mouse click on/near the slider SmallChange – change in the Value property for a mouse click on an arrow at the end TickFrequency - for TrackBar only, the number of units between tick marks With min=0 and max=1000, if Tick Frequency is 100, 10 tick marks are shown on the bar

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Coding for Scrollable Controls Any change to the position of a scroll bar generates a Scroll event Allows program to react to a shift in scroll bar Standard prefixes for these controls Horizontal scroll bar is hsb Vertical scroll bar is vsb TrackBar is tb Tutorial 12-4 demonstrates how to set up Scroll events and use of these controls

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Inhertance 12.7 Inheritance Allows a New Class to be Based on an Existing Class The New Class Inherits the Accessible Member Variables, Methods, and Properties of the Class on Which It Is Based

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Why Inheritance? Inheritance allows new classes to derive their characteristics from existing classes The Student class may have several types of students such as GraduateStudent ExchangeStudent StudentEmployee These can become new classes and share all the characteristics of the Student class Each new class would then add specialized characteristics that differentiate them

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Base and Derived Classes The Base Class is a general-purpose class that other classes may be based on A Derived Class is based on the base class and inherits characteristics from it Can think of the base class as a parent and the derived class as a child

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide The Vehicle Class (Base Class) Consider a Vehicle class with the following: Private variable for number of passengers Private variable for miles per gallon Public property for number of passengers (Passengers) Public property for miles per gallon (MilesPerGallon) This class holds general data about a vehicle Can create more specialized classes from the Vehicle class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide The Truck Class (Derived Class) Declared as: Truck class derived from Vehicle class Inherits all non-private methods, properties, and variables of Vehicle class Truck class defines two properties of its own MaxCargoWeight – holds top cargo weight FourWheelDrive – indicates if truck is 4WD Public Class Truck Inherits Vehicle ' Other new properties ' Additional methods End Class

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Instantiating the Truck Class Instantiated as: Values stored in MaxCargoWeight and FourWheelDrive properties Properties declared explicitly by Truck class Values also stored in MilesPerGallon and Passengers properties Properties inherited from Vehicle class Dim pickUp as New Truck() pickUp.Passengers = 2 pickUp.MilesPerGallon = 18 pickUp.MaxCargoWeight = 2000 Pickup.FourWheelDrive = True

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overriding Properties and Methods Sometimes a base class property procedure or method must work differently for a derived class Can override base class method or property Must write the method or property as desired in the derived class using same name When an object of the derived class accesses the property or calls the method VB uses overridden version in derived class Version in base class is not used

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Property Override Example Vehicle class has no restriction on number of passengers But may wish to restrict the Truck class to two passengers at most Can override Vehicle class Passengers property by: Coding Passengers property in derived class Specify Overridable in base class property Specify Overrides in derived class property

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overridable Base Class Property Public Overridable Property Passengers() As Integer Get Return intPassengers End Get Set(ByVal value As Integer) intPassengers = value End Set End Property Overridable keyword added to base class property procedure

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overridden Derived Class Property Public Overrides Property Passengers() As Integer Get Return MyBase.Passengers End Get Set(ByVal value As Integer) If value >= 1 And value <= 2 Then MyBase.Passengers = value Else MessageBox.Show("Passengers must be 1 or 2", _ "Error") End If End Set End Property Overrides keyword and new logic added to derived class property procedure

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overriding a method is similar to a property Specify Overridable and Overrides keywords An overridable base class method An overriding derived class method Slide Overriding Methods Public Overridable Sub ProcedureName() Public Overridable Function ProcedureName() As DataType Public Overrides Sub ProcedureName() Public Overrides Function ProcedureName() As DataType

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overriding the ToString Method Every programmer created class is derived from a built-in class named Object Object class has a method named ToString which returns a fully-qualified class name Method can be overridden to return a string representation of data stored in an object

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Object class ToString method is Overridable Vehicle class might override the ToString method as shown below Slide ToString Override Example ' Overriden ToString method Public Overrides Function ToString() As String ' Return a string representation ' of a vehicle. Dim str As String str = "Passengers: " & intPassengers.ToString & _ " MPG: " & sngMPG.ToString Return str End Function

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Base & Derived Class Constructors A constructor (named New) may be defined for both the base class and a derived class When a new object of the derived class is created, both constructors are executed The constructor of the base class will be called first Then the constructor of the derived class will be called

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Protected Members In addition to Private and Public, the access specifier may be Protected Protected base class members are treated as public to classes derived from this base Protected base class members are treated as private to classes not derived from this base Tutorial 12-5 provides an opportunity to work with base and derived classes