Student Guide Object-Oriented Programming in Visual Basic

20 downloads 727 Views 455KB Size Report
Database Programming. Chapter ... Supplementary course content is provided in a PDF file in the ... NET Programming in a Nutshell . ..... A Practical Example .
Object-Oriented Programming in Visual Basic

Student Guide Revision 3.0

Object Innovations Course 4201

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

ii

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

Rev. 3.0

Using Visual Studio 2008

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

iii

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

iv

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

v

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

vi

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

vii

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

viii

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

ix

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

x

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

xi

.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 .............................................................................................. 530 Lab 14 ......................................................................................................................... 531 Summary ..................................................................................................................... 532 Appendix A Learning Resources............................................................................... 539

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

xii

IntroVb

Chapter 6

Chapter 6

Exception Handling

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

177

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

178

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

179

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

180

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

181

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

182

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

183

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

184

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

185

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

186

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

187

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

188

IntroVb

Chapter 6

Types of Exceptions • There are actually many types of exceptions in Visual Basic, including those listed in the table below. Exception System.FormatException

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

189

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

190

IntroVb

Chapter 6

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?

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

191

IntroVb

Chapter 6

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

192

IntroVb

Chapter 6

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

193

IntroVb

Chapter 6

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

Sub Main() f, c As Single goodInput As Boolean = False 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 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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

214

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

215

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

216

IntroVb

Chapter 7

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)

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

217

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

218

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

219

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

220

IntroVb

Chapter 7

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 someAcct.Name = "Jean M."

' Reading the name ' 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() someAcct.SetName("Jean M.")

Rev. 3.0

' Reading the name ' Changing the name

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

221

IntroVb

Chapter 7

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

Rev. 3.0

' Reading the name

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

222

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

223

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

224

IntroVb

Chapter 7

WriteOnly Properties • There are also times when a property must be writeonly. − 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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

225

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

226

IntroVb

Chapter 7

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)

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

227

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

228

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

229

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

230

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

231

IntroVb

Chapter 7

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) Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

232

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

233

IntroVb

Chapter 7

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)

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

234

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

235

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

236

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

237

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

238

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

239

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

240

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

241

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

242

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

243

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

244

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

245

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

246

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

247

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

248

IntroVb

Chapter 7

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 ByVal ByVal ByVal Private Private Private Private

Event TransactionOccurred( _ transType As TransactionType, _ theAccount As BankAccount, _ amount As Decimal) m_acctNo As Integer m_owner As String m_balance As Decimal 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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

249

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

250

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

251

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

252

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

253

IntroVb

Chapter 7

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 c2 c3 c3

= = = +

Rev. 3.0

5 10 3 1 = 4

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

254

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

255

IntroVb

Chapter 7

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

256

IntroVb

Chapter 7

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

257

IntroVb

Chapter 7

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 Chap07\University\Version1 Chap07\University\Version2

Work area Solution 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:

gradePoints hrsAttempted hrsEarned

Data Type String String (will hold Freshman, Sophomore, Junior, or Senior) Short Byte Byte

Property Name Classification HoursEarned GPA

Notes It gets or puts the name attribute It gets the classification attribute (ReadOnly) It gets the hrsEarned attribute (ReadOnly) It gets the value gradePoints / hrsAttempted (ReadOnly)

Attribute name classification

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

258

IntroVb

Chapter 7

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

259

IntroVb

Rev. 3.0

Chapter 7

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

260

IntroVb

Chapter 13

Chapter 13

Database Programming

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

473

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

474

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

475

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

476

IntroVb

Chapter 13

ADO.NET Architecture (Cont’d) • The figure illustrates the overall architecture of ADO.NET. Application

Disconnected Access Connected Access

.NET Data Provider

DataSet

XML Data

Database

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

477

IntroVb

Chapter 13

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

478

IntroVb

Chapter 13

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 IDbCommand IDataReader IDbDataAdatpter IDbTransaction IDataParameter

OleDbConnection OleDbCommand OleDbDataReader OleDbDataAdapter OleDbTransaction OleDbParameter

SqlConnection SqlCommand SqlDataReader SqlDataAdapter SqlTransaction SqlParameter

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

479

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

480

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

481

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

482

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

483

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

484

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

485

IntroVb

Chapter 13

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 Wait time before terminating command attempt How CommandText is interpreted (e.g. Text, StoredProcedure) The IDbConnection used by the command The parameters collection Cancel the execution of an IDbCommand Obtain an IDataReader for retrieving data (SELECT) Execute a SQL command such as INSERT, DELETE, etc.

CommandTimeout CommandType Connection Parameters Cancel ExecuteReader ExecuteNonQuery

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

486

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

487

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

488

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

489

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

490

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

491

IntroVb

Chapter 13

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

Relation

Table

Constraints

Constraint

Rev. 3.0

Primary Key

Columns

Rows

Data Column

Data Row

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

492

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

493

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

494

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

495

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

496

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

497

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

498

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

499

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

500

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

501

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

502

IntroVb

Chapter 13

Performing a Query (Cont’d) 20. When you are satisfied with your query, click OK.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

503

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

504

IntroVb

Chapter 13

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

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

505

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

506

IntroVb

Chapter 13

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 Chap13\BankGui\Step1 Chap13\BankGui\Step2

Database:

OIC\Data\SimpleBank.mdf

(do your work here) (backup of starter code) (answer)

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

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

507

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

508

IntroVb

Chapter 13

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 Demos\ShowBooks Chap13\ShowBooks\Step1 Chap13\ShowBooks\Step2

(do your work here – starter code) (continue in-class demo) (backup of starter code) (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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

509

IntroVb

Chapter 13

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.

Rev. 3.0

Copyright © 2008 Object Innovations Enterprises, LLC All Rights Reserved

510