134
Object Innovations Course 4201 Student Guide Revision 3.0 Object-Oriented Programming in Visual Basic

Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Embed Size (px)

Citation preview

Page 1: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Object Innovations Course 4201

Student Guide Revision 3.0

Object-Oriented Programming in Visual Basic

Page 2: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC ii All Rights Reserved

Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Authors: Robert J. Oberg and Dana Wyatt Special Thanks: Ernani Cecon, Jr. Copyright ©2008 Object Innovations Enterprises, LLC All rights reserved.. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Page 3: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 .NET: What You Need to Know Chapter 2 Fundamentals of Visual Basic Programming Chapter 3 Control Structures Chapter 4 Procedures Chapter 5 Advanced Data Types Chapter 6 Exception Handling Chapter 7 Object-Oriented Programming Chapter 8 Inheritance Chapter 9 Interfaces and Collections Chapter 10 Introduction to Windows Forms Chapter 11 Windows Forms Controls Chapter 12 User Interface Features Chapter 13 Database Programming Chapter 14 New Features in Visual Basic 2008 Appendix A Learning Resources

Electronic File Supplements

Supplement1.pdf Using Visual Studio 2008

Page 4: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• The course software installs to the root directory c:\OIC\IntroVb.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The CaseStudy directory contains a case study in multiple steps.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

− Supplementary course content is provided in a PDF file in the Supplements directory. Code examples for the supplement are in the directory Supp1.

• Data files install to the directory c:\OIC\Data.

Page 5: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1 .NET: What You Need to Know .............................................................. 1 Getting Started ................................................................................................................ 3 .NET: What Is Really Happening ................................................................................... 4 .NET Programming in a Nutshell ................................................................................... 5 .NET Program Example.................................................................................................. 6 Viewing the Assembly.................................................................................................... 7 Viewing Intermediate Language..................................................................................... 8 Understanding .NET ....................................................................................................... 9 Creating a Console Application .................................................................................... 10 Visual Studio Solutions................................................................................................. 11 Starter Code .................................................................................................................. 12 Using the Visual Studio Text Editor............................................................................. 13 IntelliSense.................................................................................................................... 14 Build and Run the Project ............................................................................................. 15 Pausing the Output........................................................................................................ 16 Visual Basic and GUI Programs ................................................................................... 17 .NET Documentation .................................................................................................... 18 Summary ....................................................................................................................... 19

Chapter 2 Fundamentals of Visual Basic Programming........................................... 21 Visual Basic .................................................................................................................. 23 Hello, World ................................................................................................................. 24 Compiling, Running (Command Line) ......................................................................... 25 Program Structure ......................................................................................................... 26 Namespaces................................................................................................................... 28 Project Imports.............................................................................................................. 29 Startup Object ............................................................................................................... 30 Naming Standards......................................................................................................... 31 Keywords ...................................................................................................................... 32 Multiple-File Program Structure................................................................................... 33 Using Procedures .......................................................................................................... 34 Data Types .................................................................................................................... 35 IEEE 754 Floating Point Standard................................................................................ 36 Data Type Ranges ......................................................................................................... 38 Literals .......................................................................................................................... 39 Variables ....................................................................................................................... 41 Initialization of Variables ............................................................................................. 43 Type Checking .............................................................................................................. 44 Weak Type Checking Example .................................................................................... 45 Constants....................................................................................................................... 47 Data Conversions .......................................................................................................... 48 Operators and Expressions............................................................................................ 50 Arithmetic Operators .................................................................................................... 51

Page 6: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC vi All Rights Reserved

String Operators ............................................................................................................ 53 Relational Operators ..................................................................................................... 54 Logical Operators.......................................................................................................... 55 Bitwise Operators.......................................................................................................... 57 Assignment Operators................................................................................................... 58 Operator Precedence ..................................................................................................... 59 Console I/O ................................................................................................................... 60 Console Input ................................................................................................................ 61 Console Output ............................................................................................................. 62 Placeholders .................................................................................................................. 63 A Practical Example ..................................................................................................... 66 Lab 2 ............................................................................................................................. 68 Summary ....................................................................................................................... 69

Chapter 3 Control Structures ...................................................................................... 73 Control Structures ......................................................................................................... 75 If/Then Statement.......................................................................................................... 76 If/Then/Else Statement.................................................................................................. 77 Payroll Example............................................................................................................ 79 Select Case Statement ................................................................................................... 81 Lab 3A .......................................................................................................................... 82 Looping ......................................................................................................................... 83 Do/Loop Statement ....................................................................................................... 84 Leap Year Example....................................................................................................... 86 Exiting Do Loops Prematurely ..................................................................................... 88 While Statement............................................................................................................ 89 For/Next Statement ....................................................................................................... 90 A Random Number Example........................................................................................ 91 Lab 3B........................................................................................................................... 94 Continue Statement....................................................................................................... 95 Summary ....................................................................................................................... 96

Chapter 4 Procedures ................................................................................................... 99 Modules....................................................................................................................... 101 Subroutines ................................................................................................................. 102 ByVal Parameters ....................................................................................................... 103 ByRef Parameters ....................................................................................................... 105 Functions..................................................................................................................... 106 A Game Example........................................................................................................ 108 Access, Modules, and Scope....................................................................................... 113 Scope........................................................................................................................... 114 Scope Example – Part 1 .............................................................................................. 115 Scope Example – Part 2 .............................................................................................. 116 Scope Example – Part 3 .............................................................................................. 117 Static Variables ........................................................................................................... 118 Overloading................................................................................................................. 119 Optional Parameters.................................................................................................... 122 Variable Length Parameter Lists ................................................................................ 124

Page 7: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC vii All Rights Reserved

Lab 4A ........................................................................................................................ 126 Lab 4B......................................................................................................................... 127 Summary ..................................................................................................................... 128

Chapter 5 Advanced Data Types............................................................................... 131 Arrays.......................................................................................................................... 133 Initializing Arrays ....................................................................................................... 134 Using UBound ............................................................................................................ 135 An Example Using Arrays .......................................................................................... 136 Multi-Dimensional Arrays .......................................................................................... 138 Arrays are a Reference Type....................................................................................... 139 Reference Assignment Issues ..................................................................................... 140 Jagged Arrays.............................................................................................................. 141 An Example Using Jagged Arrays.............................................................................. 143 Dynamic Arrays .......................................................................................................... 146 Releasing Memory for the Array ................................................................................ 148 System.Array .............................................................................................................. 149 System.Array Functions.............................................................................................. 150 Lab 5A ........................................................................................................................ 151 Enumerations .............................................................................................................. 152 System.Enum .............................................................................................................. 154 System.Enum Functions ............................................................................................. 155 Structures .................................................................................................................... 156 With Statement............................................................................................................ 157 Structure Assignment.................................................................................................. 158 An Example Using Structures..................................................................................... 159 Lab 5B......................................................................................................................... 163 Pass-by-Value versus Pass-by-Reference ................................................................... 164 Value Types vs. Reference Types............................................................................... 165 Using ByVal with Value Types .................................................................................. 166 Using ByRef with Value Types .................................................................................. 167 Using ByVal with Reference Types ........................................................................... 168 Summary ..................................................................................................................... 172

Chapter 6 Exception Handling .................................................................................. 177 Handling Errors........................................................................................................... 179 Visual Basic Exception Handling ............................................................................... 182 Exception Message Demo........................................................................................... 183 System.Exception........................................................................................................ 184 Exception Flow of Control.......................................................................................... 185 Handling Multiple Exceptions .................................................................................... 187 Throwing Exceptions .................................................................................................. 188 Types of Exceptions.................................................................................................... 189 Context and Stack Unwinding .................................................................................... 190 Exception Handling Strategies.................................................................................... 191 Fahrenheit/Celsius Version 1...................................................................................... 192 Fahrenheit/Celsius Version 2...................................................................................... 193 Fahrenheit/Celsius Version 3...................................................................................... 194

Page 8: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC viii All Rights Reserved

Fahrenheit/Celsius Version 4...................................................................................... 196 Inner Exceptions ......................................................................................................... 198 Custom Exceptions ..................................................................................................... 200 Lab 6 ........................................................................................................................... 201 Summary ..................................................................................................................... 202

Chapter 7 Object-Oriented Programming ............................................................... 205 Object-Oriented Programming.................................................................................... 207 Objects in Software..................................................................................................... 208 Abstraction and Encapsulation ................................................................................... 209 Classes......................................................................................................................... 210 Defining a Class in Visual Basic ................................................................................ 211 Defining Data Members.............................................................................................. 212 Defining Methods ....................................................................................................... 213 Creating Objects.......................................................................................................... 215 Using Objects.............................................................................................................. 216 Assigning Object References...................................................................................... 217 Garbage Collection ..................................................................................................... 219 Me ............................................................................................................................... 220 Properties .................................................................................................................... 221 Defining Properties ..................................................................................................... 222 ReadOnly Properties ................................................................................................... 224 WriteOnly Properties .................................................................................................. 225 Shared Attributes ........................................................................................................ 226 Shared Methods and Properties .................................................................................. 228 An Arithmetic Calculator Example ............................................................................ 229 Constructors and Initialization.................................................................................... 231 Defining Constructors................................................................................................. 232 Default Constructor..................................................................................................... 235 Shared Constructor...................................................................................................... 237 Constructor Examples................................................................................................. 238 ReadOnly Members .................................................................................................... 239 Constant Members ...................................................................................................... 240 Events.......................................................................................................................... 241 Defining Events .......................................................................................................... 242 Restrictions on Event Procedures ............................................................................... 243 Raising Events ............................................................................................................ 244 Trapping Events Using WithEvents............................................................................ 245 Trapping Events Dynamically .................................................................................... 247 A Banking Example.................................................................................................... 249 ToString in User-Defined Classes .............................................................................. 252 Operator Overloading ................................................................................................. 254 Lab 7 ........................................................................................................................... 256 Summary ..................................................................................................................... 257

Chapter 8 Inheritance................................................................................................. 261 Inheritance................................................................................................................... 263 Inheritance Hierarchy.................................................................................................. 264

Page 9: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC ix All Rights Reserved

Defining a Derived Class ............................................................................................ 265 A Simple Example: Types of People .......................................................................... 266 .NET’s Object Class.................................................................................................... 270 Controlling Base Class Construction .......................................................................... 271 Derived Class Construction ........................................................................................ 272 Derived Class Constructors......................................................................................... 273 Need For Protected Access Modifier.......................................................................... 275 Access Control ............................................................................................................ 276 Using Protected Access............................................................................................... 277 Exceptions................................................................................................................... 280 Defining Custom Exceptions ...................................................................................... 281 Using Custom Exceptions........................................................................................... 282 Shadowing Base Class Methods ................................................................................. 283 Polymorphism............................................................................................................. 287 Defining a Method as Overridable.............................................................................. 289 Overriding a Method................................................................................................... 290 Using Heterogeneous Collections with Polymorphic Methods .................................. 291 Abstract Classes .......................................................................................................... 293 Not Inheritable Classes ............................................................................................... 295 Type Conversions in Inheritance ................................................................................ 296 CType.......................................................................................................................... 298 Lab 8 ........................................................................................................................... 299 Summary ..................................................................................................................... 300

Chapter 9 Interfaces and Collections........................................................................ 305 Components and OO in Visual Basic ......................................................................... 307 Interfaces..................................................................................................................... 308 Interfaces in Visual Basic ........................................................................................... 310 Implementing an Interface .......................................................................................... 311 Using an Interface ....................................................................................................... 312 Multiple Interfaces ...................................................................................................... 313 Using Multiple Interfaces ........................................................................................... 316 TypeOf ... Is and Dynamic Interfaces ......................................................................... 318 Interfaces in Visual Basic and COM .......................................................................... 320 Resolving Ambiguity in Interfaces ............................................................................. 321 .NET Interfaces ........................................................................................................... 324 Arrays of User-Defined Objects ................................................................................. 325 Implementing IComparable ........................................................................................ 327 Lab 9A ........................................................................................................................ 329 Collections .................................................................................................................. 330 ArrayList ..................................................................................................................... 331 ArrayList Methods ...................................................................................................... 332 Example: StringList ................................................................................................... 333 IEnumerable and IEnumerator.................................................................................... 334 Using Enumerators...................................................................................................... 335 Collections of User-Defined Objects .......................................................................... 336 Account Class ............................................................................................................. 337

Page 10: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC x All Rights Reserved

Collection Interfaces ................................................................................................... 338 ICollection................................................................................................................... 339 IList ............................................................................................................................. 340 Default Properties ....................................................................................................... 341 Using the Item Property .............................................................................................. 342 Lab 9B......................................................................................................................... 343 Writing Generic Code ................................................................................................. 344 Using a Class of Object............................................................................................... 345 Generic Types ............................................................................................................. 346 Generic Example......................................................................................................... 347 Generic Client Code.................................................................................................... 348 System.Collections.Generic........................................................................................ 349 Lab 9C......................................................................................................................... 350 Summary ..................................................................................................................... 351

Chapter 10 Introduction to Windows Forms ........................................................... 357 Windows Forms .......................................................................................................... 359 Creating a Windows Forms App................................................................................. 360 Aligning Controls........................................................................................................ 364 Setting the Tab Order.................................................................................................. 365 Partial Classes ............................................................................................................. 366 Windows Forms Event Handling................................................................................ 367 Add Events for a Control ............................................................................................ 368 Events using the Wizard Bar....................................................................................... 369 Events Documentation................................................................................................ 370 Closing a Form............................................................................................................ 371 ListBox Control .......................................................................................................... 372 ListBox Example ........................................................................................................ 373 My............................................................................................................................... 374 Command Line Arguments......................................................................................... 375 Lab 10 ......................................................................................................................... 376 Summary ..................................................................................................................... 377

Chapter 11 Windows Forms Controls ...................................................................... 383 Common Properties .................................................................................................... 385 Common Events.......................................................................................................... 387 Event Handling ........................................................................................................... 388 Sample Controls.......................................................................................................... 389 Using a Label .............................................................................................................. 390 Using Mnemonics ....................................................................................................... 391 Using a Text Box ........................................................................................................ 392 Using a Button ............................................................................................................ 394 Lab 11A ...................................................................................................................... 395 Using a Radio Button and Group Box ........................................................................ 396 Using a Check Box ..................................................................................................... 399 Using the ToolTip Control.......................................................................................... 402 Lab 11B....................................................................................................................... 405 Using a ListBox Control ............................................................................................. 406

Page 11: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC xi All Rights Reserved

Adding ListBox Items................................................................................................. 408 Removing ListBox Items ............................................................................................ 410 Selecting an Item in a List Box................................................................................... 411 Using a ComboBox Control........................................................................................ 412 Flexible Events Handlers ............................................................................................ 413 Timer Control.............................................................................................................. 415 Lab 11C....................................................................................................................... 417 Summary ..................................................................................................................... 418

Chapter 12 User Interface Features.......................................................................... 425 Dialog Boxes............................................................................................................... 427 MessageBox................................................................................................................ 428 Custom Dialogs........................................................................................................... 430 Adding a Custom Dialog ............................................................................................ 431 Using DialogResult..................................................................................................... 433 Displaying a Dialog .................................................................................................... 434 Tab Order and Focus................................................................................................... 435 Initializing a Custom Dialog....................................................................................... 436 Changing the Behavior of a Button’s DialogResult ................................................... 438 Lab 12A ...................................................................................................................... 439 Modeless Dialogs........................................................................................................ 440 Managing the Relationship between Forms................................................................ 441 Programming the Apply and Close Buttons ............................................................... 442 Enabling / Disabling the Apply Button....................................................................... 443 Common Dialogs ........................................................................................................ 444 Using a Common Dialog Control ............................................................................... 445 Menus.......................................................................................................................... 447 MenuStrip Control ...................................................................................................... 448 A Calculator Example Application............................................................................. 449 Calculator Starter Code............................................................................................... 450 Attaching a Menu to a Form ....................................................................................... 452 Configuring Items in a Menu...................................................................................... 453 Testing the Menu ........................................................................................................ 455 Responding to Menu Events ....................................................................................... 457 Changing Menu Item Appearance .............................................................................. 459 Modified SetOperation() Method ............................................................................... 460 ContextMenuStrip Control.......................................................................................... 461 Example: Integrating a Context Menu into an Application ....................................... 462 Context Menu Events.................................................................................................. 463 Handling Multiple Events ........................................................................................... 464 Lab 12B....................................................................................................................... 466 Summary ..................................................................................................................... 467

Chapter 13 Database Programming.......................................................................... 473 ADO.NET ................................................................................................................... 475 ADO.NET Architecture .............................................................................................. 476 .NET Data Providers................................................................................................... 478 Programming with ADO.NET Interfaces ................................................................... 479

Page 12: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC xii All Rights Reserved

.NET Namespaces....................................................................................................... 480 Connected Data Access............................................................................................... 481 Sample Database......................................................................................................... 482 Example: Connecting to SQL Server.......................................................................... 483 ADO.NET Class Libraries .......................................................................................... 484 Connecting to an OLE DB Data Provider................................................................... 485 Using Commands........................................................................................................ 486 Creating a Command Object....................................................................................... 487 ExecuteNonQuery....................................................................................................... 488 Using a Data Reader ................................................................................................... 489 Data Reader: Code Example....................................................................................... 490 Lab 13A ...................................................................................................................... 491 Disconnected Datasets ................................................................................................ 492 Data Adapters.............................................................................................................. 493 Data Bound Controls................................................................................................... 494 DataGridView Control................................................................................................ 495 DataGridView Sample Program ................................................................................. 496 DataGridView Demo .................................................................................................. 497 Performing a Query..................................................................................................... 502 Lab 13B....................................................................................................................... 505 Summary ..................................................................................................................... 506

Chapter 14 New Features in Visual Basic 2008........................................................ 511 Local Type Inference .................................................................................................. 513 Local Type Inference – Example................................................................................ 514 Object Initializers........................................................................................................ 515 Array Initializers ......................................................................................................... 516 Anonymous Types ...................................................................................................... 517 Partial Methods ........................................................................................................... 518 Partial Method Definition ........................................................................................... 519 Partial Method Implementation .................................................................................. 520 Main Program ............................................................................................................. 521 Running the Example.................................................................................................. 522 Extension Methods...................................................................................................... 523 Extension Methods Example ...................................................................................... 524 Lambda Expressions ................................................................................................... 525 Named Method............................................................................................................ 526 Lambda Expression Example ..................................................................................... 527 Language-Integrated Query (LINQ) ........................................................................... 528 LINQ Example............................................................................................................ 529 Using IEnumerable<T> .............................................................................................. 530 Lab 14 ......................................................................................................................... 531 Summary ..................................................................................................................... 532

Appendix A Learning Resources............................................................................... 539

Page 13: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 177 All Rights Reserved

Chapter 6

Exception Handling

Page 14: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 178 All Rights Reserved

Exception Handling

Objectives

After completing this unit you will be able to:

• Describe the Visual Basic exception handling philosophy.

• Build robust applications that trap and handle exceptions using Try and Catch.

• Generate exceptions when problems occur in a program.

Page 15: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 179 All Rights Reserved

Handling Errors

• One of the things all programmers must face is how to handle errors that occur during program execution.

• Traditionally, we use conditional statements to test for all known errors.

− If we recognize an error, we respond to it

• This approach suffers from several problems.

− Code that is needed to detect all the errors can sometimes make it difficult to determine what the code is actually trying to do.

− It can be difficult to detect all errors in large programs.

• The following procedure, attempts to perform mathematical calculations based on input data.

− See the program ErrorHandling.

− It must return a success code to indicate whether it was able to perform the calculation.

Page 16: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 180 All Rights Reserved

Handling Errors (Cont'd)

Function Calculate(ByVal op1 As Integer, _ ByVal op As Char, ByVal op2 As Integer, _ ByRef answer As Integer) As Integer ' Check the operator and perform the ' calculation (if relevant) Select Case op Case "+"c answer = op1 + op2 Case "-"c answer = op1 - op2 Case "*"c answer = op1 * op2 Case "/"c If op2 = 0 Then Return 1 answer = op1 / op2 Case Else Return 2 End Select Return 0 End Function

Page 17: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 181 All Rights Reserved

Handling Errors (Cont'd)

• The meaning of these codes must be known so that they can be used.

successCode = Calculate(operand1, op, operand2, _ result) Select Case successCode Case 0 Console.WriteLine("Result = {0}", result) Case 1 Console.WriteLine("Divide by zero") Case 2 Console.WriteLine("Invalid op") End Select

− In addition, Visual Basic programmers are not forced to capture the return value of functions.

− This means that some programmers may not detect that the function failed to calculate the result and may inadvertently use the result, or the program might crash.

Page 18: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 182 All Rights Reserved

Visual Basic Exception Handling

• Visual Basic .NET introduces an exception handling mechanism is similar to that found in languages like C#, C++, Java, and Ada.

• Exceptions are implemented by the .NET Common Language Runtime, so exceptions can be thrown in an assembly written in one .NET language and caught in an assembly written in another.

• Exception handling is accomplished via the following:

− An error is generated by throwing an exception.

− An error is handled by catching the exception.

− Code that might encounter an exception is enclosed in a try block.

Page 19: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 183 All Rights Reserved

Exception Message Demo

• The program ExceptionMessageDemo illustrates basic use of Try and Catch. It displays information about the exception.

Imports System Module ExceptionMessagesDemo Sub Main() Dim num As Integer Try Console.WriteLine( _ "Enter positive number: ") num = Convert.ToInt32(Console.ReadLine()) ' Catching a system generated exception ' (probably from input that could not be ' converted to an Integer) Catch e As System.Exception Console.WriteLine("Message: {0}", _ e.Message) Console.WriteLine("Source: {0}", _ e.Source) Console.WriteLine("Target Site: {0}", _ e.TargetSite) Console.WriteLine("Stack Trace: {0}", _ e.StackTrace) Console.WriteLine("To String: {0}", _ e.ToString) num = 0 End Try End Sub End Module

Page 20: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 184 All Rights Reserved

System.Exception

• System.Exception is the .NET class that contains information about an exception.

• It contains several properties, including the following:

− Message returns a string containing information about the exception.

− Source returns a string containing the name of the application or object that threw the exception.

− TargetSite returns a string containing the name of the procedure that threw the exception.

− StackTrace returns a string with stack trace information identifying the point at which the exception was encountered.

− InnerException returns a reference to another exception that was active when the current exception was thrown.

• In the example shown previously, the properties have the following values when non-numeric data is entered in the program:

Message: Input string was not in a correct format. Source: mscorlib Target Site: Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuffer ByRef, System.Globalization.NumberFormatInfo, Boolean) Stack Trace: ...

Page 21: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 185 All Rights Reserved

Exception Flow of Control

• The general structure of code which might encounter an exception is shown below:

Try ' code that might cause an exception Catch variable-name As Exception-data-type1 ' code to handle this type of exception [ Catch variable-name As Exception-data-typeN ' code to handle this type of exception ...] [ Finally ' code that executes regardless of whether ] ' an exception was thrown End Try

• Exceptions are caught in one or more Catch blocks that immediately follow Try.

− Because there are many types of exceptions, there can be many Catch blocks (one for each type of exception expected).

− Each catch handler has a parameter specifying the data type of the exception that it can handle, and it can use the properties of the parameter to respond to the exception appropriately.

− When an exception is thrown, the first catch handler that matches the exception data type is executed, and then control passes to the statement just after the catch block(s).

• If no exception is thrown inside the Try block, all the Catch handlers are skipped.

Page 22: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 186 All Rights Reserved

Exception Flow of Control (Cont'd)

• The Finally clause, if included, is executed regardless of whether or which Catch handler was executed.

• For example, if you needed to access a file for data, you might write the following code:

Try ' Open the file ' Read the data Catch e As Exception ' Respond to an error Finally ' Check the file, and if open, close it End Try

Page 23: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 187 All Rights Reserved

Handling Multiple Exceptions

• For example, the following code segment illustrates the handling of an IndexOutOfRange exception and a FormatException.

Dim numList(99), nextAvail As Integer ... Do While True ... Try Console.Write("Enter next number: ") numList(nextAvail) = _ Convert.ToInt32(Console.ReadLine()) nextAvail += 1 Catch boundsErr As IndexOutOfRangeException ' respond to an error that indicates nextAvail ' is not in the range 0-99 Catch badDataErr As FormatException ' respond to an error that indicates the data ' entered was non-numeric Catch e As Exception ' respond to an unknown error End Try Loop

Page 24: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 188 All Rights Reserved

Throwing Exceptions

• Exceptions can be generated by the system or can be specifically thrown with a Throw statement.

− In this case, the system will throw an exception if the data cannot be converted to an integer.

Dim num As Integer Console.Write("Enter your age: ") num = Convert.ToInt32(Console.ReadLine())

• You can also programmatically throw an exception when your application recognizes an error condition.

− By throwing an exception when an application error is detected, the programmer can treat system-generated exceptions and application errors in the same manner.

Dim payRate As Decimal Try Console.Write("Enter a pay rate: ") payRate = Convert.ToDecimal(Console.ReadLine()) If payRate < 5.15 or payRate > 75 Then Throw New Exception("Pay rate is invalid!") End If Catch e As Exception ' The pay rate was not entered correctly... ' either a conversion problem or a range problem Console.WriteLine("Pay rate error: {0}", _ e.Message) End Try

Page 25: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 189 All Rights Reserved

Types of Exceptions

• There are actually many types of exceptions in Visual Basic, including those listed in the table below.

Exception

Description

System.FormatException This exception is thrown when the format of an argument does not meet the parameter specifications of the method.

System.IndexOutOfRangeException This exception is thrown when an attempt is made to access an element outside the bounds of the array.

System.InvalidCastException This exception is thrown for invalid conversions.

System.NullReferenceException This exception is thrown when an attempt is made to use a null object reference.

System.OutOfMemoryException This exception is thrown when memory is insufficient to continue program execution.

System.OverflowException This exception is thrown when an arithmetic or conversion operation generates an overflow.

System.RankException This exception is thrown when an array with the wrong number of dimensions is passed to a procedure.

System.StackOverflowException This exception is thrown when the program stack overflows. It is typically caused by unbounded recursion.

Page 26: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 190 All Rights Reserved

Context and Stack Unwinding

• Whenever a program executes in Visual Basic, it places local variables for Main onto the program stack.

− If a nested block or another procedure is called, a new “context” is encountered.

− The system places a new record on the program stack and again places all local variables in the new record on the stack.

• Whenever an exception occurs, the system examines the current context to determine whether an exception handler exists for the exception.

− If so, the exception handler is called.

− If an exception is not handled in the current context, the exception is passed to successively higher contexts until it is finally handled, or until the top-level procedure fails to catch it and it is handled by a default system handler.

• When the higher context is entered, Visual Basic adjusts the stack properly, a process known as stack unwinding.

− Stack unwinding involves cleaning up local variables on the program stack so that the garbage collector can deallocate them.

Page 27: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 191 All Rights Reserved

Exception Handling Strategies

• It is probably more difficult to learn good exception handling strategies than it is to learn the mechanics of Try, Catch, and Throw.

• Among other questions, these come to mind:

− Where should I put the Try block?

− How big/small should the Try block be?

− Must every procedure have a Try statement?

− What should I do in a Catch block?

Page 28: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 192 All Rights Reserved

Fahrenheit/Celsius Version 1

• We illustrate exception handling with several versions of a program to convert from Fahrenheit to Celsius.

− See the folder FToCExample for all these examples.

• Although this code executes properly and does not fail when the user enters bad data, the programmer simply displays a message and exits the application when an exception is encountered.

Public Sub Main() Dim f, c As Single Try Console.Write("Enter temp (in Fahrenheit): ") f = Convert.ToSingle(Console.ReadLine()) c = (f - 32) * 5 / 9 Console.WriteLine("{0}F = {1}C", f, c) Catch e As Exception Console.WriteLine("Error:" & e.Message) Exit Sub End Try End Sub

− The basic problem with this example is that there are so many lines of code in the Try block, you have no idea what caused the error so you must treat the situation as "conversion failed" and exit the process.

Page 29: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 193 All Rights Reserved

Fahrenheit/Celsius Version 2

• In this next version of the program, we introduce corrective behavior in our Catch statement for user input.

− If an exception is found during the conversion of input data, the program loops back and asks the user for data again and again and...

Public Sub Main() Dim f, c As Single Dim goodInput As Boolean = False ' Loop until the user enters good data Do While Not goodInput Try Console.Write( _ "Enter temp (in Fahrenheit): ") f = Convert.ToSingle(Console.ReadLine()) goodInput = True Catch e As Exception Console.WriteLine("Error:" & e.Message) End Try Loop ' Process the data Try c = (f - 32) * 5 / 9 Console.WriteLine("{0}F = {1}C", f, c) Catch e As Exception Console.WriteLine("Error:" & e.Message) Exit Sub End Try End Sub

Page 30: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 194 All Rights Reserved

Fahrenheit/Celsius Version 3

• Many people would not be happy with the previous version because it asks for a temperature, in Fahrenheit, over and over until good data is entered.

− In this version, we introduce a limit to the number of times that user may try to enter a Fahrenheit value.

Public Sub Main() Dim f, c As Single Dim goodInput As Boolean = False Dim numChancesLeft As Byte Try ' Loop until the user enters good data ' (max 3 times) numChancesLeft = 3 Do While Not goodInput Try Console.Write( _ "Enter temp (in Farenheit): ") f = Convert.ToSingle(Console.ReadLine()) goodInput = True Catch e As Exception Console.WriteLine("Error:" & e.Message) numChancesLeft -= 1 If numChancesLeft <= 0 Then Throw New System.Exception( _ "Failed to enter good data " & _ " after 3 attempts") End If End Try

Page 31: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 195 All Rights Reserved

Fahrenheit/Celsius Version 3 (Cont'd)

Loop ' Process the data c = (f - 32) * 5 / 9 Console.WriteLine("{0}F = {1}C", f, c) Catch e As Exception Console.WriteLine("Error:" & e.Message) Exit Sub End Try End Sub

• The biggest problem with this version is that it is becoming hard to read.

− We haven't used procedures effectively.

Page 32: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 196 All Rights Reserved

Fahrenheit/Celsius Version 4

• This solution is quite robust.

− We build procedures for specific functionality.

Sub Main() Dim f, c As Single ' Convert a temperature in Fahrenheit ' to Celsius Try f = GetTemperature() c = FToC(f) Console.WriteLine("{0}F = {1}C", f, c) Catch e As Exception Console.WriteLine("Error:" & e.Message) Exit Sub End Try End Sub ' Read a single precision value Public Function GetSingle() As Single Return Convert.ToSingle(Console.ReadLine()) End Function

Page 33: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 197 All Rights Reserved

Fahrenheit/Celsius Version 4 (Cont'd)

' Prompt the user for a Fahrenheit value and read ' the user's response Public Function GetTemperature() As Single Dim f As Single Dim numChancesLeft As Byte = 3 Do While True Try Console.Write( _ "Enter temp (in Fahrenheit): ") f = GetSingle() Return f Catch e As Exception Console.WriteLine("Error:" & e.Message) numChancesLeft -= 1 If numChancesLeft <= 0 Then Throw New System.Exception( _ "Failed to enter good data " & _ " after 3 attempts") End If End Try Loop End Function ' Converts Fahrenheit to Celsius Public Function FToC(ByVal f As Single) As Single Return (f - 32) * 5 / 9 End Function

Page 34: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 198 All Rights Reserved

Inner Exceptions

• Throwing an exception from inside a Catch statement, we lose information about the original exception.

• However, we can retain that information by passing it as a parameter while constructing the new exception.

• The original exception is then available through the InnerException property of the new exception.

− See FToCExample\Inner.

Module FToCExample Sub Main() Dim f, c As Single ' Convert a temperature in Fahrenheit ' to Celsius Try f = GetTemperature() c = FToC(f) Console.WriteLine("{0}F = {1}C", f, c) Catch e As Exception Console.WriteLine("Error:" & e.Message) If e.InnerException IsNot Nothing Then Console.WriteLine(" Original Error:" _ & e.InnerException.Message) End If Exit Sub End Try End Sub

− Note use of the IsNot operator, introduced in .NET 2.0, which makes the If test somewhat easier to read.

Page 35: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 199 All Rights Reserved

Inner Exceptions (Cont'd)

' Read a single precision value Public Function GetSingle() As Single Return Convert.ToSingle(Console.ReadLine()) End Function ' Prompt the user for a Fahrenheit value and read ' the user's response Public Function GetTemperature() As Single Dim f As Single Dim numChancesLeft As Byte = 3 Do While True Try Console.Write( _ "Enter temp (in Fahrenheit): ") f = GetSingle() Return f Catch e As Exception Console.WriteLine("Error:" & e.Message) numChancesLeft -= 1 If numChancesLeft <= 0 Then Throw New System.Exception( _ "Failed to enter good data " & _ " after 3 attempts", e) End If End Try Loop End Function ' Converts Fahrenheit to Celsius Public Function FToC(ByVal f As Single) As Single Return (f - 32) * 5 / 9 End Function End Module

Page 36: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 200 All Rights Reserved

Custom Exceptions

• You may create your own exception types using Visual Basic by deriving a new class from System.Exception.

• For example, in a payroll application, you might create exceptions such as InvalidPayException or InvalidEmployeeTypeException.

• We will discuss this process in detail in the inheritance chapter.

Page 37: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 201 All Rights Reserved

Lab 6

New Car Loans Version 2

In this lab, you will use exception handling techniques to make sure your New Car Loan program can recover from data entry errors.

Detailed instructions are contained in the Lab 6 write-up at the end of the chapter.

Suggested time: 45 minutes

Page 38: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 202 All Rights Reserved

Summary

• Visual Basic uses Try blocks and Catch handlers to identify where exceptions are expected and how a program should respond to them.

• Exceptions may be generated by the procedures in the .NET library, or you may raise exceptions using a Throw statement.

• The .NET Framework Class Library provides a System.Exception class, which is used to gather information about where exceptions occur.

• Many types of exceptions, which are derived from System.Exception, exist in the .NET library and are thrown by various .NET procedures when an exception occurs.

Page 39: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 203 All Rights Reserved

Lab 6

New Car Loan Version 2

Introduction In this lab, you build modify your New Car Loan program so that it will not terminate abnormally if the user enters bad data. Suggested Time: 45 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab6\CarLoan Starter code

Chap02\CarLoan\Version1 Backup of starter code Chap06\CarLoan\Version2 Answer Chap06\CarLoan\Version3 Answer to optional part

Instructions 1. Build and run the starter code. (If you prefer, you may instead work from you own

solution to the lab from Chapter 2. Delete the provided starter files, and copy your files from the Lab 2 work area.)

2. Design and code an exception handling strategy so that, if any specific piece of data entered is bad, the user will be prompted about the type of data they should enter and then the program will terminate.

3. Build and test your application.

4. [OPTIONAL] If time permits, give the user one additional chance to enter each piece of bad data before terminating.

Page 40: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 6

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 204 All Rights Reserved

Page 41: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 205 All Rights Reserved

Chapter 7

Object-Oriented Programming

Page 42: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 206 All Rights Reserved

Object-Oriented Programming

Objectives

After completing this unit you will be able to:

• Describe the object-oriented features of Visual Basic.

• Build a class containing both methods and properties.

• Define and use constructors.

• Use shared data and shared methods.

• Implement a class that triggers events and handles those events in client code.

• Describe the operator overloading feature of Visual Basic 2005.

Page 43: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 207 All Rights Reserved

Object-Oriented Programming

• Visual Basic .NET was designed to be a truly object-oriented language.

− It has capabilities that rival those of languages like Java, C++ and C#.

• The term object has an intuitive real-world meaning.

− There are concrete, tangible objects, such as a ball, an automobile, and an airplane.

− There are also more abstract objects that have a definite intellectual meaning, such as a committee, a patent, or an insurance contract.

• Objects have both attributes (or characteristics) and operations that can be performed upon them.

− A ball has a size, a weight, a color, and so on.

− Operations may be performed on the ball, such as throw, catch, and drop.

• There can be relationships among classes of objects.

− A specialization relationship exists when an object is a specialization of another type (ex: an automobile is a special kind of vehicle).

− A whole/part relationship exists when an object is part of another type (ex: such as an automobile consists of an engine, a chassis, wheels, and other parts).

Page 44: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 208 All Rights Reserved

Objects in Software

• Software objects correspond to objects in the real world.

− By explicitly describing the real-world system in terms of objects, you can understand the system more explicitly and precisely.

− A software system implemented in this way tends to be more faithful to the real system, and it can be changed more readily when the real system is changed.

• An object is a software entity containing data and related functions as a self-contained module.

• Objects hold state and specify behavior.

− The state of the object consists of the owner of the account, an ID for the account, and the account balance.

− The behavior of the account consists of functions to deposit or withdraw an amount from the account and to obtain an account statement.

Page 45: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 209 All Rights Reserved

Abstraction and Encapsulation

• Objects provide the means for abstraction and encapsulation.

• An abstraction captures the essential features of an entity, suppressing unnecessary details.

− All instances of an abstraction share these common features.

− Abstraction helps us deal with complexity.

• The implementation of an abstraction should be hidden from the rest of the system, or encapsulated.

− The public side is what the rest of the system knows, while the private side implements the public side.

− Data itself is private, walled off from the rest of the program and can be accessed only through functions (or methods) in the public interface.

• Encapsulated provides us two kinds of protection:

− Internal data is protected from corruption.

− Users of the object are protected from changes in the representation.

Page 46: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 210 All Rights Reserved

Classes

• A class groups all objects with common behavior and common structure.

− A class allows production of new objects of the same type.

− An object is an instance of some class.

− We refer to the process of creating an individual object as instantiation.

Page 47: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 211 All Rights Reserved

Defining a Class in Visual Basic

• To code a class in Visual Basic, you must first add a new class module to your project.

− You can do this by right-clicking on the name of the project and choosing Add | Add Class.

− If you name the class BankAccount, the IDE generates a new file named BankAccount.vb.

Class BankAccount End Class

Page 48: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 212 All Rights Reserved

Defining Data Members

• To define data members of a class, you typically add them as private data members.

− A common naming convention is to prefix the variable names with m_ to indicate that they are members of the class.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String Private m_balance As Decimal ... End Class

• By defining the class itself as a Public class, you are indicating that the class can be used throughout this application.

• The code that we discuss is in the BankAccount example, which has several versions.

Page 49: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 213 All Rights Reserved

Defining Methods

• To define the behavioral aspects of the class, you must add methods or procedures.

• Each method that is accessible by anyone who creates a BankAccount object is defined as a public procedure.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String Private m_balance As Decimal Public Sub Open(ByVal acctNo As Integer, _ ByVal name As String, _ Optional ByVal initialBalance As Decimal = 0) m_acctNo = acctNo m_name = name m_balance = initialBalance End Sub Public Function Deposit(ByVal amount As _ Decimal) As Boolean ' Check for a negative deposit If amount < 0 Then Return False ' Process deposit m_balance += amount Return True End Function

Page 50: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 214 All Rights Reserved

Defining Methods (Cont'd)

Public Function Withdraw(ByVal amount As _ Decimal) As Boolean ' Check for a negative withdrawal If amount < 0 Then Return False ' Check for overdraft condition If amount > m_balance Then Return False ' Process withdrawal m_balance -= amount Return True End Function Public Function GetAcctNo() As Integer Return m_acctNo End Function Public Function GetOwner() As String Return m_owner End Function Public Function GetBalance() As Decimal Return m_balance End Function End Class

− This is Version 1 of BankAccount.

Page 51: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 215 All Rights Reserved

Creating Objects

• Classes, in Visual Basic, are reference types.

− When you declare a variable of a class type, you are only obtaining memory for a reference to an object of the class type.

− No memory is allocated for the object itself.

Dim myAcct as BankAccount ' myAcct is a reference to a BankAccount object; ' no object exists yet

• To create, or instantiate, an object in Visual Basic, you must use the New keyword.

myAcct = New BankAccount() ' a BankAccount object now exists and myAcct is ' a reference to it

• Once an object exists, you may interact with it using any public member of the class.

myAcct.Open (101, "Dana") myAcct.Deposit(1200) Console.WriteLine( _ "Account {0} has balance of {1:C}", _ myAcct.GetAcctNo(), myAcct.GetBalance())

• The New keyword can be used when you declare the variable.

Dim myAcct as New BankAccount ' myAcct is a reference to a BankAccount object ' was created in this declaration

Page 52: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 216 All Rights Reserved

Using Objects

• To invoke methods for a particular object, you use dot (.) notation.

Dim dlwAcct, mwwAcct as New BankAccount dlwAcct.Open(158, "Dana") mwwAcct.Open(263, "Mark") dlwAcct.Deposit(150) mwwAcct.Deposit(150)

• If you attempt to reference the private members of an object from outside the implementation of a method, you will get a syntax error.

mwwAcct.m_balance = 1000000 Error Message: BankAccount.m_balance is Private, and is not accessible in this context.

Page 53: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 217 All Rights Reserved

Assigning Object References

• It is important to have a firm understanding of the way that object references work in order to effectively write object-oriented programs in Visual Basic.

Dim myAcct as New BankAccount Dim yourAcct as New BankAccount myAcct.Open(1551, "Brenda", 2250) yourAcct.Open(1552, "Glenda", 2000)

Page 54: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 218 All Rights Reserved

Assigning Object References (Cont'd)

• Because these variables are reference types, when you make an assignment to an object variable, you are only assigning the reference.

• There is no copying of data. yourAcct = myAcct ' yourAcct now refers to same object that ' myAcct does

Page 55: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 219 All Rights Reserved

Garbage Collection

• Assignment of object references in Visual Basic can lead to orphaned objects.

− For example, when the variable myAcct in the previous example was assigned to yourAcct, yourAcct became orphaned.

• Such an object (or “garbage”) takes up memory in the computer, which can now never be referenced.

• The common language runtime automatically reclaims the memory of unreferenced objects.

− This process is known as garbage collection.

• Garbage collection takes up some execution time, but it is a great convenience for programmers, helping to avoid a common program error known as a memory leak.

Page 56: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 220 All Rights Reserved

Me

• Sometimes, it is convenient to be able to access the current object reference from within a method.

• Visual Basic defines the keyword Me for this purpose.

− Me is a special variable that always refers to the current object instance.

• An alternative implementation of the Deposit method shown above might be as follows:

Public Function Deposit(ByVal amount As Decimal) _ As Boolean ' Check for a negative deposit If amount < 0 Then Return False ' Process deposit Me.m_balance += amount Return True End Function

− Me refers to the object that invoked the method.

myAcct.Deposit (100) ' in this invocation of Deposit, Me refers to ' the instance myAcct yourAcct.Deposit (100) ' in this invocation of Deposit, Me refers to ' the instance yourAcct

Page 57: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 221 All Rights Reserved

Properties

• Visual Basic provides a special type of procedure available to classes, modules, and structures called a property procedure.

− In Visual Basic, a property looks like a public data member of an object from the perspective of the user of the object.

− For example, if the BankAccount class has a public property called Name that accesses the account’s m_name data member, you could write the following code:

Dim someAcct As New BankAccount someAcct.Open("Jean C.", 850) Dim n As String n = someAcct.Name ' Reading the name someAcct.Name = "Jean M." ' Changing the name

• Properties allow the user of an object to interact with the object in a new way.

− If the property Name shown above did not exist, we would have to provide GetName and SetName methods in the BankAccount class and write the following code:

Dim someAcct As New BankAccount someAcct.Open("Jean C.", 850) Dim n As String n = someAcct.GetName() ' Reading the name someAcct.SetName("Jean M.") ' Changing the name

Page 58: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 222 All Rights Reserved

Defining Properties

• To define a property, its name and data type must be specified.

− In addition, code must be written for both the Get and Set portions of the property.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String Private m_balance As Decimal ... Public Property Name() As String Get Return m_name End Get Set(ByVal Value As String) m_name = Value End Set End Property ... End Class

• Whenever the property Name is used on the left-hand side of an assignment statement, Visual Basic invokes the Set property.

someAcct.Name = "Jean M." ' Changing the name

• If the property is used in any other context, the Get property is invoked.

Dim n As String n = someAcct.Name ' Reading the name

Page 59: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 223 All Rights Reserved

Defining Properties (Cont'd)

• Property procedures may also have parameters passed to them.

− For example, this can happen when a property represents an underlying array.

• If a Student object maintained an array of test scores, a property called Score could be defined that allowed the following type of access:

Dim zack As New Student zack.Score(0) = 84 ... For i = 0 to 3 Console.WriteLine("Test Score #{0} = {1}", _ i, zack.Score(i)) Next

• The Student class, as described above, would minimally contain the following code:

Public Class Student ... Private m_scores(9) As Integer Public Property Score(ByVal index As Byte) _ As Integer Get Return m_scores(index) End Get Set(ByVal Value As Integer) m_scores(index) = Value End Set End Property End Class

Page 60: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 224 All Rights Reserved

ReadOnly Properties

• Sometimes, a property must be read-only.

− That is, it should never be used on the left-hand side of an assignment statement.

− In these cases, the property is designated read-only using the ReadOnly keyword, and it does not have a Set portion.

Public Class BankAccount Private m_acctNo As Integer ... Public ReadOnly Property AcctNo() As Integer Get Return m_acctNo End Get End Property ... End Class

• Properties are illustrated in Version 2 of BankAccount.

Page 61: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 225 All Rights Reserved

WriteOnly Properties

• There are also times when a property must be write-only.

− That is, you can never use it to get the value of a property.

− In these cases, the property is designated write-only using the WriteOnly keyword and does not have a Get portion.

• In this alternate version of the BankAccount class, it would define a PIN (personal identification number) that must be passed in for any withdrawal to succeed.

− The PIN would be defined when the account was opened.

− It could not be accessed, but it could be changed.

Public Class BankAccount ... Private m_PIN as String Public WriteOnly Property PIN() As String Set(ByVal Value As String) m_PIN = Value End Set End Property ... End Class

Page 62: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 226 All Rights Reserved

Shared Attributes

• In Visual Basic, each instance of a class has its own set of unique values for the data members of the class.

− This type of data is called instance data.

• Sometimes, however, it is useful to have a data value or procedure associated with the entire class, as opposed to individual instances.

− Such a member is called a shared member.

• To define a shared data member, add the keyword Shared to the data declaration.

− We can modify our BankAccount class to keep track of the next available account number by adding a shared data member to the class.

− See Version 3.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String Private m_balance As Decimal Private Shared m_nextAccountNum As Integer = 101 ... End Class

− This variable is associated with the class, not with a particular instance of the class.

− Therefore, all instances of a BankAccount use the same variable m_nextAccountNum.

Page 63: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 227 All Rights Reserved

Shared Attributes (Cont'd)

• The shared data member can be used in methods. Public Sub Open(ByVal name As String, _ Optional ByVal initialBalance As Decimal = 0) m_acctNo = m_nextAccountNum m_name = name m_balance = initialBalance m_nextAccountNum += 1 End Sub

• The following code illustrates one use of the new Open method.

myAcct.Open("Dana")

• Like instance data members, shared data members can be either Public or Private.

− To access a public shared member, you must use the dot notation with the name of the class replacing the name of the object.

Public Class BankAccount ... Public Shared BankName As String _ = "First State Bank" Private Shared m_nextAccountNum As Integer = 101 ... End Sub ... Console.WriteLine(BankAccount.BankName)

Page 64: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 228 All Rights Reserved

Shared Methods and Properties

• A class may also declare methods and properties as shared.

− To do this, add the keyword Shared to the method or property declaration.

• A shared method or property can be called without instantiating the class.

− You use the dot notation, with the class name in front of the dot.

− Because you can call a shared procedure without an instance, it can only access local variables, shared variables of the class, and global variables. It cannot access instance data members.

Page 65: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 229 All Rights Reserved

An Arithmetic Calculator Example

• The following example defines a class that contains nothing but Shared methods.

− Rather than defining a set of global functions, we have defined a Calculator class.

− The example is in the Calculator folder.

Public Class Calculator Public Shared Function Add(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 + op2 End Function Public Shared Function Subtract(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 - op2 End Function Public Shared Function Multiply(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 * op2 End Function Public Shared Function Divide(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 / op2 End Function End Class

Page 66: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 230 All Rights Reserved

Arithmetic Calculator (Cont'd)

• The following simple program uses methods in the Calculator class to achieve specific mathematical calculations.

Module Driver Sub Main() Console.Write("Enter operand 1: ") Dim operand1 As Double = _ Convert.ToDouble(Console.ReadLine()) Console.Write("Enter operand 2: ") Dim operand2 As Double = _ Convert.ToDouble(Console.ReadLine()) Console.WriteLine("Add result: {0}", _ Calculator.Add(operand1, operand2)) Console.WriteLine("Subtract result: {0}", _ Calculator.Subtract(operand1, operand2)) Console.WriteLine("Multiply result: {0}", _ Calculator.Multiply(operand1, operand2)) Console.WriteLine("Divide result: {0}", _ Calculator.Divide(operand1, operand2)) End Sub End Module

• Output of this test program might be as follows: Enter operand 1: 3 Enter operand 2: 9 Add result: 12 Subtract result: -6 Multiply result: 27 Divide result: 0.333333333333333

Page 67: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 231 All Rights Reserved

Constructors and Initialization

• When an object is created, what initial values are assigned to the instance data?

− Visual Basic because variables are automatically initialized to a default value.

• However, what do you do if you want to perform your own initialization?

− The initialization can be performed by calling some special function such as the BankAccount’s Open method.

− The class can initialize data members in the member declarations.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String = "Unknown" Private m_balance As Decimal ... End Class

− The class can provide a special function called the constructor that can be used to initialize objects on a per-instance basis.

Page 68: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 232 All Rights Reserved

Defining Constructors

• A constructor is a special method that is automatically called when an object is created using New.

• In Visual Basic, the constructor must be defined as a subroutine named New.

− It is typically defined as Public, and it may define a parameter list.

Public Class BankAccount Private m_acctNo As Integer Private m_name As String Private m_balance As Decimal Private Shared m_nextAccountNum As Integer = 101 Public Sub New(Optional ByVal name As String _ = "", Optional ByVal initialBalance As _ Decimal = 0) m_acctNo = m_nextAccountNum m_name = name m_balance = initialBalance m_nextAccountNum += 1 End Sub ... End Class

• The New keyword is used to instantiate object instances.

− It is during this New operation that you pass arguments to the constructor.

Dim natAcct As BankAccount natAcct = New BankAccount("Natalie", 1700)

Page 69: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 233 All Rights Reserved

Defining Constructors (Cont'd)

• The New keyword can also be used in the same statement that declares the reference variable.

Dim britAcct As New BankAccount("Brittany", 1500)

• Because the BankAccount constructor defines optional parameters, it could also be invoked using the following statement:

Dim zackAcct As New BankAccount()

− In this case, the variable zackAcct references a BankAccount object that had the name initialized to the empty string and the balance initialized to zero.

• Just like other procedures in Visual Basic, constructors can be overloaded.

− However, you do not use the Overloads keyword on the procedure definition.

Public Class BankAccount Private m_acctNo As Integer Private m_owner As String Private m_balance As Decimal Private Shared m_nextAccountNum As Integer = 101 Public Sub New() m_acctNo = m_nextAccountNum m_name = "" m_balance = 0 m_nextAccountNum += 1 End Sub

Page 70: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 234 All Rights Reserved

Defining Constructors (Cont'd)

Public Sub New(ByVal name As String) m_acctNo = m_nextAccountNum m_name = name m_balance = 0 m_nextAccountNum += 1 End Sub Public Sub New(ByVal name As String, _ ByVal initialBalance As Decimal) m_acctNo = m_nextAccountNum m_name = name m_balance = initialBalance m_nextAccountNum += 1 End Sub ... End Class

− The first constructor (with no parameters) allows us to create an object without specifying any initial values:

Dim firstAcct As New Account()

− The second constructor (with one String parameter) allows us to create an object by specifying an owner's name:

Dim secondAcct As New Account("Jen")

− The third constructor (with a String parameter and a Decimal parameter) allows us to create an object by specifying an owner's name and a starting balance:

Dim secondAcct As New Account("Jay", 1617)

Page 71: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 235 All Rights Reserved

Default Constructor

• If you do not define a constructor in your class, Visual Basic will implicitly create one for you.

− This constructor is called the default constructor, and it has no parameters.

− The compiler-supplied default constructor will initialize member variables with the value specified on the variable declaration.

• The default constructor is an important constructor, because it is what allows the following declaration to occur:

Dim someAcct As New Account

• However, if you provide any form of a constructor in your class, the compiler no longer supplies a version of the default constructor for you.

Public Class BankAccount ... Public Sub New(ByVal name As String, _ ByVal initialBalance As Decimal) ... End Sub ... End Class

Page 72: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 236 All Rights Reserved

Default Constructor (Cont'd)

• The following line of code compiles successfully: Dim myAcct as New BankAccount("Dana", 1200)

• However, this next declaration generates a compiler error that says the required arguments are not provided:

Dim yourAcct as New BankAccount()

• This syntax error occurs because we have provided a constructor.

− If we had provided no constructors, Visual Basic would have provided a default constructor.

− But because we provided one constructor, we must provide all allowable versions.

Page 73: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 237 All Rights Reserved

Shared Constructor

• Standard constructors are called each time an instance of a class is created.

• Visual Basic also provides a shared constructor that is called only once, before any object instances are created.

− A shared constructor is defined by prefixing the constructor with the keyword Shared.

− A shared constructor can take no parameters and has no access modifier.

• You can use a shared constructor to initialize a shared variable.

− Using a shared constructor, we can initialize the variable to a starting value that is calculated at runtime, or retrieved from a database.

Public Class BankAccount ... Private Shared m_nextAccountNum As Integer Shared Sub New() Dim rand As New Random() m_nextAccountNum = 101 + rand.Next(10000) End Sub ... End Class

− The Next method of the .NET System.Random class to returns a random number that is less than the specified maximum.

Page 74: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 238 All Rights Reserved

Constructor Examples

• Our BankAccount program provides a number of illustrations of the use of constructors.

− In Versions 1 through 3 there is a default constructor.

− Version 4A provides a single constructor with optional arguments.

− Version 4B provides three overloaded constructors.

− Version 4C provides a shared constructor.

Page 75: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 239 All Rights Reserved

ReadOnly Members

• They keyword ReadOnly can be applied to instance variables to force its value to be constant.

− This means that it can be initialized in the constructor, but it cannot be changed in any other procedure.

− Any attempt to change it results in a syntax error.

− Although using ReadOnly isn’t ever required, using it on variables that cannot change is good design

Public Class BankAccount Private ReadOnly m_acctNo As Integer ... Public Sub New(Optional ByVal owner As String _ = "", Optional ByVal initialBalance As _ Decimal = 0) m_acctNo = m_nextAccountNum ... End Sub ... End Class

Page 76: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 240 All Rights Reserved

Constant Members

• Visual Basic also provides the ability to define Const member declarations of a class.

− When a data member is defined as Const, it is also a Shared member!

− If it is Public, you can access it from outside the class using dot notation and the class name instead of an object variable.

• Unlike a ReadOnly member, a Const member cannot be changed in a constructor.

Public Class BankAccount Private ReadOnly m_acctNo As Integer Private m_name As String = "Unknown" Private m_balance As Decimal Private Shared m_nextAccountNum As Integer = 101 Private Const m_bankName As String _ = "First State Bank" ... End Class

Page 77: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 241 All Rights Reserved

Events

• Visual Basic provides the ability for a class to fire events that can then be caught by the user using an instance of the class.

− Events are essentially callbacks to the user’s code that occur when certain predefined data transitions occur.

− For example, a Database class might define the events ConnectionCompleted and ConnectionTerminated that are fired when connections are made or broken to the underlying data source.

• There is an important difference between events and exceptions that must be noted.

− Events are callbacks to a user’s code that can be trapped or ignored.

− Exceptions must be caught -- an uncaught exception will terminate the program.

• We illustrate events with two more versions of our BankAccount example program.

− Versions 5A illustrates static event handling using the WithEvents keyword.

− Version 5B illustrates dynamic event handling.

Page 78: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 242 All Rights Reserved

Defining Events

• Events are defined by adding an event declaration to the class using the Event keyword.

− Events must have a name and an optional list of parameters that will be sent to the event handler.

• We will add a TransactionOccurred event to the BankAccount class.

− The TransactionOccurred event passes back to the user’s code the type of transaction that occurred and the amount of the transaction.

− To provide a robust solution, we have introduced enumeration values representing the different types of transactions.

Public Class BankAccount Public Enum TransactionType Deposit Withdrawal End Enum Public Event TransactionOccurred( _ ByVal transType As TransactionType, _ ByVal amount As Decimal) Private m_acctNo As Integer ... End Class

Page 79: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 243 All Rights Reserved

Restrictions on Event Procedures

• There are some restrictions on event procedures.

− They cannot have return values.

− They cannot have optional parameters.

− They cannot have a variable length parameter list.

Page 80: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 244 All Rights Reserved

Raising Events

• Events are raised by the class when data transitions happen within an object that indicates the event should occur.

• To raise a specific event, the RaiseEvent statement is used.

• For example, the TransactionOccurred event is raised in the Deposit and Withdraw methods when they have successfully completed their activities.

Public Class BankAccount ... Public Function Deposit(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False m_balance += amount RaiseEvent TransactionOccurred( _ TransactionType.Deposit, amount) Return True End Function Public Function Withdraw(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False If amount > m_balance Then Return False m_balance -= amount RaiseEvent TransactionOccurred( _ TransactionType.Withdrawal, amount) Return True End Function End Class

Page 81: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 245 All Rights Reserved

Trapping Events Using WithEvents

• Events are trapped by the code that creates and uses a particular instance of the class.

• To trap events generated for a particular object, you must declare the variable using the WithEvents keyword.

− To listen for events on a particular object, the variable must not be declared as a local variable in a procedure.

− It must be declared at the class or module level.

Private WithEvents dlwAcct As BankAccount

− After the variable declaration is complete, you will notice that the variable appears in the upper-left dropdown box on the editor window.

Page 82: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 246 All Rights Reserved

Using WithEvents (Cont'd)

• You can trap events by selecting the object from the left dropdown box on the wizard bar, and then selecting the event from the right dropdown box on the wizard bar.

− Code for the handler function will be generated automatically.

− The Handles keyword indicates that this procedure is an event handler.

− The objectName . eventName notation that follows the keyword Handles indicates that this function is invoked when the TransactionOccurred event is generated for the dlwAcct object.

Public Sub dlwAcct_TransactionOccurred( _ ByVal transType As BankAccount.TransactionType, _ ByVal amount As Decimal) _ Handles dlwAcct.TransactionOccurred Select Case transType Case BankAccount.TransactionType.Deposit ... Case BankAccount.TransactionType.Withdrawal ... End Select End Sub

Page 83: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 247 All Rights Reserved

Trapping Events Dynamically

• Although trapping events using the WithEvents keyword is easy, it is somewhat limiting.

− The event handler is attached to a specific reference variable via static code.

− Although the object that the variable references can change (by creating a new instance of the class), the variable that the event handler references cannot change.

• Visual Basic allows you to dynamically connect and disconnect events with event handler procedures.

• This is done via AddHandler and RemoveHandler.

• For example, assume that two variables of type BankAccount were defined as follows:

Private dlwAcct As New BankAccount Private mwwAcct As New BankAccount

• And assume a handler function for any TransactionOccurred event was defined as follows:

Public Sub someTransactionOccurred( _ ByVal transType As BankAccount.TransactionType, _ ByVal amount As Decimal) Select Case transType Case BankAccount.TransactionType.Deposit ... Case BankAccount.TransactionType.Withdrawal ... End Select End Sub

Page 84: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 248 All Rights Reserved

Trapping Events Dynamically (Cont'd)

• You can use the AddHandler statement to indicate that the dlwAcct.TransactionOccurred event should be sent to the someTransactionOccurred handler:

AddHandler dlwAcct.TransactionOccurred, _ someTransactionOccurred

• You can use similar logic to send the mwwTransactionOccurred event to the same handler:

AddHandler mwwAcct.TransactionOccurred, _ someTransactionOccurred

• This handler function is now called regardless of whether the dlwAcct object or the mwwAcct object generated the event.

− However, because of our event design, we are now unable to determine what object occurred inside our handler function.

Page 85: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 249 All Rights Reserved

A Banking Example

• The following class represents a slight redesign in the BankAccount class. See Version 5B.

− The TransactionOccurred event was redesigned to carry with it information as to which object generated the event.

Public Class BankAccount Public Enum TransactionType Deposit Withdrawal End Enum Public Event TransactionOccurred( _ ByVal transType As TransactionType, _ ByVal theAccount As BankAccount, _ ByVal amount As Decimal) Private m_acctNo As Integer Private m_owner As String Private m_balance As Decimal Private Shared m_nextAccountNum As Integer = 101 Public Sub New( _ Optional ByVal owner As String = "", _ Optional ByVal initialBalance As Decimal = 0) m_acctNo = m_nextAccountNum m_owner = owner m_balance = initialBalance m_nextAccountNum += 1 End Sub Public Function Deposit(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False m_balance += amount

Page 86: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 250 All Rights Reserved

A Banking Example (Cont'd)

RaiseEvent TransactionOccurred( _ TransactionType.Deposit, Me, amount) Return True End Function Public Function Withdraw(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False If amount > m_balance Then Return False m_balance -= amount RaiseEvent TransactionOccurred( _ TransactionType.Withdrawal, Me, amount) Return True End Function Public ReadOnly Property AcctNo() As Integer Get Return m_acctNo End Get End Property Public Property Owner() As String Get Return m_owner End Get Set(ByVal Value As String) m_owner = Value End Set End Property Public ReadOnly Property Balance() As Decimal Get Return m_balance End Get End Property End Class

Page 87: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 251 All Rights Reserved

A Banking Example (Cont'd)

• Here is the key code from the driver program. Dim dlwAcct, mwwAcct As BankAccount Sub Main() ' Initialize the two accounts dlwAcct = New BankAccount("Dana", 1250) mwwAcct = New BankAccount("Mark", 750) ' Associate the two accounts with event handler AddHandler dlwAcct.TransactionOccured, _ AddressOf someTransactionOccured AddHandler mwwAcct.TransactionOccured, - AddressOf someTransactionOccured ... Public Sub someTransactionOccured( _ ByVal transType As BankAccount.TransactionType, _ ByVal theAccount As BankAccount, _ ByVal amount As Decimal) Select Case transType Case BankAccount.TransactionType.Deposit Console.WriteLine( _ "Deposit of {0:C} recorded for {1}", _ amount, theAccount.AcctNo) Case BankAccount.TransactionType.Withdrawal Console.WriteLine( _ "Withdrawl of {0:C} recorded for {1}", _ amount, theAccount.AcctNo) End Select End Sub

Page 88: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 252 All Rights Reserved

ToString in User-Defined Classes

• The ToString() method that is found in all data types, such as Integer, Decimal, and Date, is also available in every class you define yourself.

− It is inherited from the Object class (more on this in the next chapter).

• Below we create two instances of a BankAccount and display them using the WriteLine() method.

− In the first case, we directly call ToString().

− In the second case, we rely upon the implicit call to ToString() to obtain the string representation for us.

Dim natAcct As New BankAccount("Natalie", 1700) Dim britAcct As New BankAccount("Brittany", 1500) Console.WriteLine(natAcct.ToString()) Console.WriteLine(britAcct)

• The program compiles and runs, but the output is a little disappointing:

BankAccountExample.BankAccount BankAccountExample.BankAccount

• The ToString() method used in our BankAccount is the one defined in the .NET class Object from which class implicitly inherits.

− The base class Object knows nothing about our class, so it displays the name of the class.

Page 89: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 253 All Rights Reserved

ToString in User-Defined Classes

• The ToString() method is an overridable method, which means that we may provide a version of it in our own class to display a more meaningful representation.

− BankAccountToString\Version1 does not override ToString(). Version 2 does override ToString().

− The String.Format function uses the same formatting techniques at Console.WriteLine, but returns the string rather than displaying it.

Public Class BankAccount ... Public Overrides Function ToString() As String Dim retVal As String retVal = String.Format( _ "Account: {0}, Owner: {1}, Balance: {2:C}", _ m_acctNo, m_name, m_balance) Return retVal End Function End Class

• The test program remains the same: Dim natAcct As New BankAccount("Natalie", 1700) Dim britAcct As New BankAccount("Brittany", 1500) Console.WriteLine(natAcct.ToString()) Console.WriteLine(britAcct)

• However, the output is what we expected: Account: 101, Owner: Natalie, Balance: $1,700.00 Account: 102, Owner: Brittany, Balance: $1,500.00

Page 90: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 254 All Rights Reserved

Operator Overloading

• Beginning with .NET 2.0, you can overload operators in Visual Basic, as has been possible in languages such as C++ and C#.

• You cannot create new operators, but you can overload many of the existing operators to be an alias for a shared method.

• The overloaded operator is used just like the built-in operator is used, except it is applied to a custom data type.

• As an example, consider ClockOperator.

− Here is the test program that uses the + operator that has been overloaded to do “clock” arithmetic (modulo 12). Note that the compiler then automatically also overloads += for you.

Dim c1 As Clock = New Clock(17) Console.WriteLine("c1 = {0}", c1.Hour) Dim c2 As Clock = New Clock(10) Console.WriteLine("c2 = {0}", c2.Hour) Dim c3 As Clock = c1 + c2 Console.WriteLine("c3 = {0}", c3.Hour) c3 += 1 Console.WriteLine("c3 + 1 = {0}", c3.Hour)

− Here is the output:

c1 = 5 c2 = 10 c3 = 3 c3 + 1 = 4

Page 91: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 255 All Rights Reserved

Operator Overloading (Cont’d)

• Here is the code defining the class Clock.

− Note use of the keyword Operator.

Public Class Clock Private m_hour As Integer Public Sub New(ByVal h As Integer) m_hour = h Mod 12 If m_hour = 0 Then m_hour = 12 End If End Sub Public Property Hour() As Integer Get Return m_hour End Get Set m_hour = Value End Set End Property Public Shared Operator +(ByVal c1 As Clock, _ ByVal c2 As Clock) As Clock Dim h As Integer = c1.hour + c2.hour Dim c3 As Clock = New Clock(h) Return c3 End Operator Public Shared Operator +(ByVal c1 As Clock, _ ByVal h2 As Integer) As Clock Dim h As Integer = c1.hour + h2 Dim c3 As Clock = New Clock(h) Return c3 End Operator End Class

Page 92: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 256 All Rights Reserved

Lab 7

Building a Class in Visual Basic

In this lab, you will build a class that represents a Student object in a university setting. The class will maintain information about the student and their GPA.

Detailed instructions are contained in the Lab 7 write-up at the end of the chapter.

Suggested time: 75 minutes

Page 93: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 257 All Rights Reserved

Summary

• Classes can represent user-defined data types.

− A class can be thought of as a template from which individual instances, or objects, can be created.

− Classes support encapsulation through attributes and methods.

− Typically, attributes are defined as Private members and methods are defined as Public members of a class.

• Because classes are reference types, when you declare a variable of a class type, you are obtaining memory only for a reference to an object of the class type.

− No memory for the object is allocated itself until New is invoked.

• The common language runtime automatically reclaims the memory of orphaned, or unreferenced, objects.

− This process is known as garbage collection.

• Initialization of objects is performed in special procedures called constructors.

• Visual Basic also provides the ability for objects to generate events to notify users of that event that some predefined action occurred.

• You can overload built-in operators in your custom classes.

Page 94: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 258 All Rights Reserved

Lab 7

Building a Class in Visual Basic

Introduction In this lab, you will build a class that represents a student at a university. It will have several properties and methods that allow you to manipulate student objects. Then you will build a main procedure that declares instances of the student class and uses them. Suggested Time: 75 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab7 Work area

Chap07\University\Version1 Solution Chap07\University\Version2 Solution to optional

Instructions 1. Create a new Visual Basic Console Application and name it University. Change the

module file name to University.vb.

2. Add a class module to the project and name the class Student. Define the following members:

Attribute Data Type name String classification String (will hold Freshman, Sophomore, Junior, or Senior) gradePoints Short hrsAttempted Byte hrsEarned Byte Property Notes Name It gets or puts the name attribute Classification It gets the classification attribute (ReadOnly) HoursEarned It gets the hrsEarned attribute (ReadOnly) GPA It gets the value gradePoints / hrsAttempted (ReadOnly) Method Notes New It accepts a value for the name attribute. CompleteCourse It accepts two parameters: grade (character) and hours (byte). If

the grade is an A, it is worth 4 points. A B is worth 3 points, etc. An F is worth 0 points. Add the grade's point value times the

Page 95: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 259 All Rights Reserved

hours for the class to gradePoints (ex: a 3 hour course with an A is worth 12 points). Add the hours to hrsAttempted. If the grade is passing, also add the hours to hrsEarned. Finally, change the classification to one of the following:

Freshman if hrsEarned < 32 Sophmore if hrsEarned < 64 Junior if hrsEarned < 96 Senior all other cases

3. In Main, declare two instances of a Student. Have each student complete several courses. Using the properties, display the student's classification, GPA, etc. after each operation.

4. Build and test your application.

[Optional] Add two events to the Student class. The first event should be called GPAWarning and should be raised whenever a student completes a course and their GPA falls below 2.0. The second event should be called TransitionToUpperclassman and occurs when the number of hours earned becomes 60 or more. In the Main subroutine, catch these events and display an informative message.

Page 96: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 7

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 260 All Rights Reserved

Page 97: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 473 All Rights Reserved

Chapter 13

Database Programming

Page 98: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 474 All Rights Reserved

Database Programming

Objectives

After completing this unit you will be able to:

• Understand the key concepts in the ADO.NET data access programming model.

• Use the ADO.NET classes to build applications that retrieve and update data from a data source.

• Use Visual Studio 2008 to efficiently implement database programs.

• Use the data binding facilities in Windows Forms and ADO.NET.

Page 99: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 475 All Rights Reserved

ADO.NET

• The .NET Framework has introduced a new set of database classes designed for loosely coupled, distributed architectures.

− These classes are referred to as ADO.NET.

• ADO.NET uses the same access mechanisms for local, client-server, and Internet database access.

− It can be used to examine data as relational data or as hierarchical (XML) data.

• ADO.NET can pass data to any component using XML and does not require a continuous connection to the database.

• A more traditional connected access model is also available.

Page 100: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 476 All Rights Reserved

ADO.NET Architecture

• The DataSet class is the central component of the disconnected architecture.

− A dataset can be populated from either a database or from an XML stream.

− From the perspective of the user of the dataset, the original source of the data is immaterial.

− A consistent programming model is used for all application interaction with the dataset.

• The second key component of ADO.NET architecture is the .NET Data Provider, which provides access to a database, and can be used to populate a dataset.

− A data provider can also be used directly by an application to support a connected mode of database access.

Page 101: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 477 All Rights Reserved

ADO.NET Architecture (Cont’d)

• The figure illustrates the overall architecture of ADO.NET.

Application

DataSet

XML Data.NET Data Provider

Database

ConnectedAccess

DisconnectedAccess

Page 102: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 478 All Rights Reserved

.NET Data Providers

• A .NET data provider is used for connecting to a database.

− It provides classes that can be used to execute commands and to retrieve results.

− The results are either used directly by the application, or else they are placed in a dataset.

• A .NET data provider implements four key interfaces:

− IDbConnection is used to establish a connection to a specific data source.

− IDbCommand is used to execute a command at a data source.

− IDataReader provides an efficient way to read a stream of data from a data source. The data access provided by a data reader is forward-only and read-only.

− IDbDataAdapter is used to populate a dataset from a data source.

• The ADO.NET architecture specifies these interfaces, and different implementations can be created to facilitate working with different data sources.

− A .NET data provider is analogous to an OLE DB provider, but the two should not be confused. An OLE DB provider implements COM interfaces, and a .NET data provider implements .NET interfaces.

Page 103: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 479 All Rights Reserved

Programming with ADO.NET Interfaces

• In order to make your programs more portable, you should endeavor to program with the interfaces rather than using specific classes directly.

− In our example programs we will illustrate using interfaces to talk to an Access database (using the OleDb data provider) and a SQL Server database (using the SqlServer data provider).

• Classes of the OleDb provider have a prefix of OleDb, and classes of the SqlServer provider have a prefix of Sql.

− The table shows a number of parallel classes between the two data providers and the corresponding interfaces.

Interface OleDb SQL Server IDbConnection OleDbConnection SqlConnection IDbCommand OleDbCommand SqlCommand IDataReader OleDbDataReader SqlDataReader IDbDataAdatpter OleDbDataAdapter SqlDataAdapter IDbTransaction OleDbTransaction SqlTransaction IDataParameter OleDbParameter SqlParameter

− Classes such as DataSet which are independent of any data provider do not have any prefix.

Page 104: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 480 All Rights Reserved

.NET Namespaces

• ADO.NET classes are found in the following namespaces:

− System.Data consists of classes that constitute most of the ADO.NET architecture.

− System.Data.OleDb contains classes that provide database access using the OLE DB data provider.

− System.Data.SqlClient contains classes that provide database access using the SQL Server data provider.

− System.Data.OracleClient contains classes that provide database access using the Oracle data provider. Both Microsoft and Oracle supply data providers for Oracle.

− System.Data.SqlTypes contains classes that represent data types used by SQL Server.

− System.Data.Common contains classes that are shared by data providers.

Page 105: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 481 All Rights Reserved

Connected Data Access

• The connection class (OleDbConnection or SqlConnection) is used to manage the connection to the data source.

− It has properties ConnectionString, ConnectionTimeout, and so forth.

− There are methods for Open, Close, transaction management, etc.

• A connection string is used to identify the information the object needs to connect to the database.

− You can specify the connection string when you construct the connection object, or by setting its properties.

− A connection string contains a series of argument = value statements separated by semicolons.

• To program in a manner that is independent of the data source, you should obtain an interface reference of type IDbConnection after creating the connection object, and you should program against this interface reference.

Page 106: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 482 All Rights Reserved

Sample Database

• Our sample database, SimpleBank, stores account information for a small bank. Two tables:

1. Account stores information about bank accounts. Columns are AccountId, Owner, AccountType and Balance. The primary key is AccountId.

2. BankTransaction stores information about account transactions. Columns are AccountId, XactType, Amount and ToAccountId. There is a parent/child relationship between the Account and BankTransaction tables.

• There are SQL Server 2005 and Access versions of this database.

− We will be using SQL Server 2005 Express Edition, which comes automatically with Visual Studio 2008.

− There is also built-in support for Access as well, so no special DBMS software is required for this chapter.

• The database files are in the folder OIC\Data.

− The SQL Server database file is SimpleBank.mdf

− The Access database file is SimpleBank.mdb.

Page 107: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 483 All Rights Reserved

Example: Connecting to SQL Server

− See SqlConnectOnly.

Imports System Imports System.Data.SqlClient Friend Class Class1 Shared Sub Main(ByVal args As String()) Dim connStr As String = _ "Data Source=.\SQLEXPRESS;AttachDbFilename= c:\OIC\Data\SimpleBank.mdf; Integrated Security=True;User Instance=True" Dim conn As New SqlConnection() conn.ConnectionString = connStr Console.WriteLine( _ "Using SQL Server to access SimpleBank") Console.WriteLine( _ "Database state: " & conn.State.ToString()) conn.Open() Console.WriteLine( _ "Database state: " & conn.State.ToString()) End Sub End Class Output: Using SQL Server to access SimpleBank Database state: Closed Database state: Open

Page 108: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 484 All Rights Reserved

ADO.NET Class Libraries

• To run a program that uses the ADO.NET classes, you must be sure to set references to the appropriate class libraries. The following libraries should usually be included:

− System.dll

− System.Data.dll

− System.Xml.dll (needed when working with datasets)

• References to these libraries are set up automatically when you create a Windows, console or ASP.NET project in Visual Studio.

− If you create an empty project, you will need to specifically add these references.

− The figure shows the references in a console project, as created by Visual Studio.

Page 109: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 485 All Rights Reserved

Connecting to an OLE DB Data Provider

• To connect to an OLE DB data provider instead, you need to change the namespace you are importing and instantiate an object of the OleDbConnection class.

− You must provide a connection string appropriate to your OLE DB provider.

− We are going to use the Jet OLE DB provider, which can be used for connecting to an Access database.

− The program JetConnectOnly illustrates connecting to the Access database SimpleBank.mdb

Imports System Imports System.Data.OleDb Friend Class Class1 Shared Sub Main(ByVal args As String()) Dim connStr As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\OIC\Data\SimpleBank.mdb" Dim conn As New OleDbConnection() conn.ConnectionString = connStr Console.WriteLine( _ "Using Access DB SimpleBank.mdb") Console.WriteLine( _ "Database state: " & conn.State.ToString()) conn.Open() Console.WriteLine( _ "Database state: " & conn.State.ToString()) End Sub End Class

Page 110: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 486 All Rights Reserved

Using Commands

• After we have opened a connection to a data source, we can create a command object, which will execute a query against a data source.

− Depending on our data source, we will create either a SqlCommand object or an OleDbCommand object.

− In either case, we will initialize an interface reference of type IDbCommand, which will be used in the rest of our code, again promoting relative independence from the data source.

• The table summarizes some of the principle properties and methods of IDbCommand.

Property or Method

Description

CommandText Text of command to run against the data source

CommandTimeout Wait time before terminating command attempt

CommandType How CommandText is interpreted (e.g. Text, StoredProcedure)

Connection The IDbConnection used by the command Parameters The parameters collection Cancel Cancel the execution of an IDbCommand ExecuteReader Obtain an IDataReader for retrieving data

(SELECT) ExecuteNonQuery Execute a SQL command such as INSERT,

DELETE, etc.

Page 111: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 487 All Rights Reserved

Creating a Command Object

• The code fragments shown below are from the ConnectedSql program, which illustrates performing various database operations on the SimpleBank database.

− For an Access version, see ConnectedJet.

• The following code illustrates creating a command object and returning an IDbCommand interface reference.

Private Shared Function CreateCommand( _ ByVal query As String) As IDbCommand Return New SqlCommand(query, sqlConn) End Function

• Note that we return an interface reference, not an object reference.

− Using the generic interface IDbCommand makes the rest of our program independent of a particular database.

Page 112: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 488 All Rights Reserved

ExecuteNonQuery

• The following code illustrates executing a SQL DELETE statement using a command object.

− We create a query string for the command, and obtain a command object for this command.

− The call to ExecuteNonQuery returns the number of rows that were updated.

Private Shared Sub RemoveAccount( _ ByVal id As Integer) Dim query As String = _ "delete from Account where AccountId = " & id Dim command As IDbCommand = CreateCommand(query) Dim numrow As Integer = _ command.ExecuteNonQuery() Console.WriteLine("{0} rows updated", numrow) End Sub

Page 113: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 489 All Rights Reserved

Using a Data Reader

• After we have created a command object, we can call the ExecuteReader method to return an IDataReader.

− With the data reader we can obtain a read-only, forward-only stream of data.

− This method is suitable for reading large amounts of data, because only one row at a time is stored in memory.

− When you are done with the data reader, you should explicitly close it. Any output parameters or return values of the command object will not be available until after the data reader has been closed.

• Data readers have an Item property that can be used for accessing the current record.

− The Item property accepts either an integer (representing a column number) or a string (representing a column name).

− The Item property is the default property and can be omitted if desired.

• The Read method is used to advance the data reader to the next row.

− When it is created, a data reader is positioned before the first row.

− You must call Read before accessing any data. Read returns true if there are more rows, and otherwise false.

Page 114: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 490 All Rights Reserved

Data Reader: Code Example

• The code illustrates using a data reader to display results of a SELECT query.

− Sample program is still in ConnectedSql.

Private Shared Sub ShowList() Dim query As String = "select * from Account" Dim command As IDbCommand = CreateCommand(query) Dim reader As IDataReader = _ command.ExecuteReader() Do While reader.Read() Console.WriteLine( _ "{0,3} {1,-10} {2:C} {3}", _ reader("AccountId"), reader("Owner"), _ reader("Balance"), reader("AccountType")) Loop reader.Close() End Sub

Page 115: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 491 All Rights Reserved

Lab 13A

Bank Database Program

In this lab, you will build a Windows Forms application that provides a graphical user interface to the Simple Bank database.

Detailed instructions are contained in the Lab 13A write-up at the end of the chapter.

Suggested time: 30 minutes

Page 116: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 492 All Rights Reserved

Disconnected Datasets

• A DataSet stores data in memory and provides a consistent relational programming model that is the same whatever the original source of the data.

− Thus, a DataSet contains a collection of tables and relationships between tables.

− Each table contains a primary key and collections of columns and constraints, which define the schema of the table, and a collection of rows, which make up the data stored in the table.

DataSet

Relationships Tables

TableRelation

Rows

Data Row

Constraints

Constraint

Primary Key Columns

Data Column

Page 117: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 493 All Rights Reserved

Data Adapters

• A data adapter provides a bridge between a disconnected dataset and its data source.

− Each .NET data provider provides its own implementation of the interface IDbDataAdapter.

− The OLE DB data provider has the class OleDbDataAdapter, and the SQL data provider has the class SqlDataAdapter.

• A data adapter has properties for SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand.

− These properties identify the SQL needed to retrieve data, add data, change data, or remove data from the data source.

• A data adapter has the Fill method to place data into a dataset. It has the Update command to update the data source using data from the dataset.

Page 118: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 494 All Rights Reserved

Data Bound Controls

• All of our demonstration programs so far have been console applications.

− We have done this in order to focus on the coding of database functionality, without being distracted by issues concerning user interface.

− Also, by catching exceptions in our command loop, we are able to conveniently display exception information, making it easy for you to experiment and observe the results, even for exceptional situations.

• Naturally, in practice you will want to create an attractive user interface, either as a Windows application or a Web application.

• In this section we will give a brief introduction to providing a graphical user interface to a database application using Windows Forms.

• There are two approaches that can be followed.

− The first is to write specific code to populate controls with data that has been retrieved from a database. You did that in Lab 13A.

− The second is to use data bound controls. We will illustrate this second approach by showing how to bind a dataset to a DataGridView control.

Page 119: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 495 All Rights Reserved

DataGridView Control

• The DataGridView control is new with .NET 2.0 and is the preferred control for interacting with tabular data.

• Binding data to a DataGridView control is simple, and is often simply a matter of setting the DataSource property.

• It will bind to any class that implements one of the following interfaces:

− IList, including one-dimensional arrays and array lists

− IListSource, including DataSet and DataTable

− IBindingList, such as GenericBindingList

− IBindingListView, such as BindingSource

• Most frequently, you will bind to a BindingSource component, which is in turn bound to a data source.

• Visual Studio 2008 provides a wizard interface to facilitate establishing bindings.

Page 120: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 496 All Rights Reserved

DataGridView Sample Program

• We’ll demonstrate using a DataGridView control in an application that accesses the SmallPub database.

− You should have SQL Server 2005 Express edition installed.

− The database file SmallPub.mdf is located in the directory c:\OIC\Data.

• This database is for use by a small publisher of technical books. There are two tables:

− Category maintains a list of categories for books.

− Book is a list of the books published.

• The sample program shows a list of all books in a category that is selected from a dropdown list.

− See ShowBooks\Step2.

Page 121: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 497 All Rights Reserved

DataGridView Demo

• We’ll create this application from scratch, using Visual Studio.

1. Create a new Windows Application ShowBooks. Save the solution of the new project in the Demos directory.

2. Increase the size of the main form somewhat, comparable to what is shown in the screen capture in the preceding page.

3. Drag a DataGridView control from the Data group in the ToolBox onto your form. Note that the “smart tag” for this control is expanded, allowing you to set up a binding.

4. Drop down Choose Data Source and click on Add Project Data Source.

Page 122: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 498 All Rights Reserved

DataGridView Demo (Cont’d)

5. Make sure that Database is specified for the source of the data. Click Next.

6. In the next screen, to choose the connection, click the New Connection button.

7. In the Add Connection dialog, make sure that SQL Server Database File is selected as the data source, and browse to the SmallPub.mdf file. You may test the connection if you wish.

8. Click OK. Back in the wizard, click Next.

9. You will be asked if you want to copy the database file to your project. Say No.

Page 123: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 499 All Rights Reserved

DataGridView Demo (Cont’d)

10. You will be asked if you want to save the connection string to the application configuration file. Leave the checkbox at Yes, and click Next.

11. In “Choose your database objects” expand Tables and check both the Book and Category tables.

12. Click Finish.

13. You will now have an opportunity to select which table in the DataSet you want to bind to the DataGridView control. (If the smart tag has closed, open it up again to finish binding the control to the project data source that you have just created.)

Page 124: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 500 All Rights Reserved

DataGridView Demo (Cont’d)

14. If necessary, open up the Project Data Sources to show the SmallPubDataSet and its tables.

15. Click on the link to the Book table.

16. Visual Studio will now create several components for you: a DataSet, a BindingSource, and a TableAdapter. See the screen capture on the following page. (At some point you will also want to resize the DataGridView control to provide adequate width for displaying all the columns.)

Page 125: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 501 All Rights Reserved

DataGridView Demo (Cont’d)

17. You will now see column headings displayed in the grid.

Build and run. You will see all the books displayed.

Page 126: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 502 All Rights Reserved

Performing a Query

• We would now like to provide a facility for the user to show only the books in a particular category.

18. Open up the smart tag again, and click on the Add Query link.

19. Name the query “BooksByCat” and specify a WHERE clause, making the entire query:

SELECT BookId, Title, CategoryId, Price FROM dbo.Book WHERE CategoryId = @CategoryId

Page 127: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 503 All Rights Reserved

Performing a Query (Cont’d)

20. When you are satisfied with your query, click OK.

Page 128: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 504 All Rights Reserved

Performing a Query (Cont’d)

21. A ToolStrip is added to your form to run the query. Build and run your application. Try entering a particular CategoryId, and then click the BooksByCat button.

22. You have a simple database query application, and you have not written a line of code!

23. Make any desired tweaks to the UI, such as making the DataGridView control larger. Change the title of your form to “Show Books By Category.” You are now at Step 1.

24. Examine Step 2, which replaces the automatically generated ToolStrip interface with your own combobox for displaying the available categories.

Page 129: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 505 All Rights Reserved

Lab 13B

Data Binding

In this lab, you will enhance the data binding demo program to specify the CategoryId by means of a dropdown combobox, which is bound to the Category table of the DataSet. You can use the code generated by Visual Studio for the ToolStrip as a guide for your own code. When done, you can delete the ToolStrip.

Detailed instructions are contained in the Lab 13B write-up at the end of the chapter.

Suggested time: 30 minutes

Page 130: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 506 All Rights Reserved

Summary

• ADO.NET provides a set of classes that can be used to interact with data providers.

• You can access data sources in either a connected or disconnected mode.

• The DataReader can be used to build interact with a data source in a connected mode.

• The DataSet can be used to interact with data from a data source without maintaining a constant connection to the data source.

• The DataSet can be populated from a database using a DataAdapter.

• You can use Visual Studio 2008 to efficiently implement database programs.

• You can easily display data from a dataset on a form by binding the dataset to a DataGridView control.

Page 131: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 507 All Rights Reserved

Lab 13A

Bank Database Program

Introduction In this lab, you will build a Windows Forms application that provides a graphical user interface to the Simple Bank database.

Suggested Time: 45 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab13A\BankGui (do your work here) Chap13\BankGui\Step1 (backup of starter code) Chap13\BankGui\Step2 (answer) Database: OIC\Data\SimpleBank.mdf Instructions 1. Build and run the starter program. Examine the code, and observe the following

features.

a. The class DB encapsulates all the ADO.NET code. In general, this is a good design, as opposed to having database code directly in the GUI. All the methods are shared, so it will not be necessary to instantiate a DB object.

Page 132: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 508 All Rights Reserved

b. The class Account encapsulates an account.

c. The file Form1.vb provides the user interface, with handlers for the Read, Previous and Next buttons. The Read button will read the database into an ArrayList, which can be traversed by the Previous and Next buttons. The number of accounts in the list will be shown in a status bar at the bottom of the form.

2. Provide a method AddAccount() in the DB class. It will be similar to the corresponding method in the ConnectedSql() program, but it will not do any output. Instead, it will return the number of rows updated to the calling program.

Public Shared Function AddAccount(ByVal owner As String, _ ByVal bal As Decimal, ByVal atype As String) As Integer Dim query As String = "insert into Account " & _ "(Owner, Balance, AccountType) values('" & owner & "', " & _ bal & ", '" & atype & "')" Dim command As IDbCommand = CreateCommand(query) conn.Open() Dim numrow As Integer = command.ExecuteNonQuery() conn.Close() Return numrow End Function 3. Provide a handler for the Add button in which you will call the AddAccount()

method.

Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click Dim owner As String = txtOwner.Text Dim balance As Decimal = Convert.ToDecimal(txtBalance.Text) Dim acctype As String = "" If radChecking.Checked Then acctype = "C" ElseIf radSavings.Checked Then acctype = "S" End If Dim numrow As Integer = DB.AddAccount(owner, balance, acctype) Dim msg As String = String.Format("{0} rows updated", numrow) MessageBox.Show(msg, "Simple Bank") End Sub 4. You may build and test at this point. Note that you do not have to specify an ID for a

new account, as the database will generate an ID automatically for you. After you have added an account, you may click Read. You should see in the status bar that there is now one more account, and by clicking Next repeatedly, you will come to the new account.

5. In a similar manner add a method RemoveAccount() and use it to implement a handler for the Delete button. Finally, add a method UpdateAccount() and use it to implement a handler for the Update button. Build and test.

Page 133: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 509 All Rights Reserved

Lab 13B

Data Binding

Introduction In this lab, you will enhance the data binding demo program to specify the CategoryId by means of a dropdown combobox, which is bound to the Category table of the DataSet. You can use the code generated by Visual Studio for the ToolStrip as a guide for your own code. When done, you can delete the ToolStrip. Suggested Time: 30 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab13B\ShowBooks (do your work here – starter code) Demos\ShowBooks (continue in-class demo) Chap13\ShowBooks\Step1 (backup of starter code) Chap13\ShowBooks\Step2 (answer) Instructions 1. If you completed the in-class demo, you may continue working in the

Demos\ShowBooks directory. Otherwise, you can use the starter code provided in the lab directory. Build and run your program to make sure it is working.

2. Drag a ComboBox onto the form. Change the DropDownStyle to DropDown and the name to cmbCat.

3. Open the smart tag.

4. Check Use data bound items. For the Data Source, select the Category table of the data set. Display Member should be Description and Value Member should be CategoryId.

Page 134: Object-Oriented Programming in Visual Basic - ITCourseware · Object-Oriented Programming in Visual Basic Rev. 3.0 Student Guide Information in this document is subject to change

IntroVb Chapter 13

Rev. 3.0 Copyright © 2008 Object Innovations Enterprises, LLC 510 All Rights Reserved

5. Build and run the program. You should see that the combobox is displaying the categories, but at this point it is not linked to populating the DataGridView control.

6. To see how we might invoke the query, examine the code generated by Visual Studio for clicking the BooksByCat button on the toolbar.

Me.bookTableAdapter.BooksByCat(Me.smallPubDataSet.Book, _ (CInt(System.Convert.ChangeType(categoryIdToolStripTextBox.Text, _ GetType(Integer))))) 7. The key is that the generated TableAdapter object has a method BooksByCat() for

invoking the parameterized query. You simply have to pass as parameters the data set table and the CategoryId.

8. Double-click the combo box to add an event handler for the SelectedIndexChanged event. Provide the following code in a helper method ShowBooks():

If cmbCat.SelectedIndex <> -1 Then Dim id As Integer = CInt(cmbCat.SelectedValue) bookTableAdapter.BooksByCat(smallPubDataSet.Book, id) End If 9. Build and run. Both user interfaces for specifying a category should now be working.

Delete the ToolStrip and clean up any stray code. Make sure that the program still works with your combo box.

10. Initially all the books are shown. To have only all the books of the current category shown initially, add a call to ShowBooks() in the Load event handler.

11. Build and exercise your program.