Basic Concepts

140
Basic Concepts Basic Concepts

description

Basic Concepts. Variables. Declaration : [ < attributelist > ] [  accessmodifier  ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] Dim [ WithEvents ] variablelist - PowerPoint PPT Presentation

Transcript of Basic Concepts

Page 1: Basic Concepts

Basic ConceptsBasic Concepts

Page 2: Basic Concepts

VariablesVariables Declaration : Declaration :

[ <[ <attributelistattributelist> ] [ > ] [ accessmodifieraccessmodifier ]  ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] DimDim [ WithEvents ] [ WithEvents ] variablelistvariablelist

attributelist : attributelist : Specifies the attributes to be applied to a Specifies the attributes to be applied to a declared programming element. Multiple attributes are declared programming element. Multiple attributes are separated by commas. separated by commas.

accessmodifier : accessmodifier : Can be one of the following:Can be one of the following: PublicPublic ProtectedProtected FriendFriend PrivatePrivate Static : Static : Specifies that one or more declared local variables Specifies that one or more declared local variables

are to remain in existence and retain their latest values are to remain in existence and retain their latest values after termination of the procedure in which they are after termination of the procedure in which they are declared.declared.

ReadOnly : ReadOnly : Specifies that a variable or property can be Specifies that a variable or property can be read but not written.read but not written.

WithEvents : WithEvents : Specifies that one or more declared member Specifies that one or more declared member variables refer to an instance of a class that can raise variables refer to an instance of a class that can raise events.events.

Page 3: Basic Concepts

ExamplesExamples Dim numberOfStudents As IntegerDim numberOfStudents As Integer Dim summary As String = "Summary of results" Dim summary As String = "Summary of results" Dim days() As Integer Dim days() As Integer Dim lastTime, nextTime, allTimes() As DateDim lastTime, nextTime, allTimes() As Date Dim finished As BooleanDim finished As Boolean Dim monitorBox As Dim monitorBox As

System.Windows.Forms.FormSystem.Windows.Forms.Form Dim a, b, c As Single, x, y As Double, i As IntegerDim a, b, c As Single, x, y As Double, i As Integer ' a, b, and c are all Single; x and y are both ' a, b, and c are all Single; x and y are both

DoubleDouble Dim bottomLabel As New Dim bottomLabel As New

System.Windows.Forms.LabelSystem.Windows.Forms.Label

Page 4: Basic Concepts

ConstantsConstants Declaring : Declaring :

[<attributelist>] [{ Public | Protected | [<attributelist>] [{ Public | Protected | Friend | Protected Friend | Private }] Friend | Protected Friend | Private }] [Shadows] constant-name [As type] = [Shadows] constant-name [As type] = initexprinitexpr

Examples :Examples :Const conPi = 3.14159265358979Const conPi = 3.14159265358979Public Const conMaxPlanets As Integer = 9Public Const conMaxPlanets As Integer = 9Const conReleaseDate = #1/1/1995#Const conReleaseDate = #1/1/1995#Public Const conVersion = "07.10.A"Public Const conVersion = "07.10.A"Const conCodeName = "Enigma“Const conCodeName = "Enigma“Const conPi2 = conPi * 2Const conPi2 = conPi * 2

Page 5: Basic Concepts

ProgrammingProgramming

Page 6: Basic Concepts

If..elseIf..else Syntax: Syntax:

If (Condition)If (Condition) ThenThenStatements executed if condition is trueStatements executed if condition is true

ElseElseStatements executed if condition is falseStatements executed if condition is false

End IfEnd If

Example:Example:If A > 10 Then If A > 10 Then

A = A + 1A = A + 1ElseElse

B = B + AB = B + AEnd IfEnd If

Page 7: Basic Concepts

If..ElseIfIf..ElseIf Example:Example:

Dim number, digits As IntegerDim number, digits As IntegerDim myString As StringDim myString As Stringnumber = 53number = 53If number < 10 ThenIf number < 10 Then

digits = 1digits = 1ElseIf number < 100 ThenElseIf number < 100 Then

digits = 2digits = 2ElseElse

digits = 3digits = 3End IfEnd IfIf digits = 1 ThenIf digits = 1 Then

myString = "One“myString = "One“ElseElse

myString = "More than one“myString = "More than one“End ifEnd if

Page 8: Basic Concepts

Select..CaseSelect..Case Syntax:Syntax:

Select Case varSelect Case var

Case 1Case 1

stmt1stmt1 // executed if var = 1// executed if var = 1

Case 2Case 2

stmt2stmt2 // executed if var = 2// executed if var = 2

Case ElseCase Else

stmt3stmt3 // executed if var is // executed if var is other than 1 and 2other than 1 and 2

End SelectEnd Select

Page 9: Basic Concepts

Continued…Continued… Example:Example:

Dim number As Integer = 8Dim number As Integer = 8Select Case numberSelect Case numberCase 1 To 5Case 1 To 5

System.Console.WriteLine("Between 1 and 5")System.Console.WriteLine("Between 1 and 5") ' The following is the only Case clause that ' The following is the only Case clause that

evaluates to True.evaluates to True. Case 6, 7, 8Case 6, 7, 8 System.Console.WriteLine("Between 6 and 8")System.Console.WriteLine("Between 6 and 8") Case 9 To 10Case 9 To 10 System.Console.WriteLine("Equal to 9 or 10")System.Console.WriteLine("Equal to 9 or 10") Case ElseCase Else System.Console.WriteLine("Not between 1 and 10")System.Console.WriteLine("Not between 1 and 10")

End SelectEnd Select

Page 10: Basic Concepts

LoopsLoops

Page 11: Basic Concepts

Looping Structure Looping Structure OverviewOverview

Visual Basic loop structures allow Visual Basic loop structures allow you to run one or more lines of code you to run one or more lines of code repetitively. You can repeat the repetitively. You can repeat the statements in a loop structure until a statements in a loop structure until a condition is condition is TrueTrue, until a condition is , until a condition is FalseFalse, a specified number of times, , a specified number of times, or once for each element in a or once for each element in a collection. collection.

Page 12: Basic Concepts

Do LoopDo Loop Repeats a block of statements while a Repeats a block of statements while a

BooleanBoolean condition is condition is TrueTrue or until the or until the condition becomes condition becomes TrueTrue..

Example:Example:Dim counter As Integer = 0Dim counter As Integer = 0

DoDo counter += 1counter += 1 If counter = 10 ThenIf counter = 10 Then check = Falsecheck = False End IfEnd If Loop Until check = FalseLoop Until check = False

Page 13: Basic Concepts

Do WhileDo While The The Do...While Do...While statement allow you to repeat a statement allow you to repeat a

block of code while a certain condition is block of code while a certain condition is TrueTrue, , or until a certain condition is or until a certain condition is TrueTrue..

For example, suppose you had a program to add For example, suppose you had a program to add a series of numbers, but you never wanted the a series of numbers, but you never wanted the sum of the numbers to be more than 100. You sum of the numbers to be more than 100. You could use the could use the Do...WhileDo...While statement to perform statement to perform the addition as follows:the addition as follows:Dim sum As Integer = 0Dim sum As Integer = 0Do While sum < 100Do While sum < 100

sum = sum + 10sum = sum + 10LoopLoop

Page 14: Basic Concepts

Do While VariationsDo While Variations First:First:

Do While(a<>0)Do While(a<>0)Console.Writeline(a)Console.Writeline(a)a = a – 1a = a – 1

LoopLoop Second:Second:

Do Do Console.Writeline(a)Console.Writeline(a)

a = a – 1a = a – 1Loop While(a<>0)Loop While(a<>0)

Page 15: Basic Concepts

For NextFor Next

For/Next loops enable you to evaluate For/Next loops enable you to evaluate a sequence of statements multiple a sequence of statements multiple times. This is unlike the If and Select times. This is unlike the If and Select statements where the program passes statements where the program passes through each statement at most once through each statement at most once during the formula's evaluation. during the formula's evaluation.

For/Next loops are best when you For/Next loops are best when you know the number of times that the know the number of times that the statements needs to be evaluated in statements needs to be evaluated in advance.advance.

Page 16: Basic Concepts

For Next ExampleFor Next Example

For i As Integer = 1 To 10For i As Integer = 1 To 10 For j As Integer = 1 To 10For j As Integer = 1 To 10 For k As Integer = 1 To 10For k As Integer = 1 To 10 ' Insert statements to operate ' Insert statements to operate

withwith current values of i, j, and k.current values of i, j, and k. Next kNext k Next jNext jNext iNext i

Page 17: Basic Concepts

For EachFor Each

The The For EachFor Each statement statement construction is similar to the construction is similar to the ForFor......NextNext loop, but it runs the loop, but it runs the statement block for each element in statement block for each element in a collection, instead of a specified a collection, instead of a specified number of times.number of times.

A A For EachFor Each......NextNext loop uses an loop uses an element variableelement variable that represents a that represents a different element of the collection different element of the collection during each repetition of the loop.during each repetition of the loop.

Page 18: Basic Concepts

For Each ExampleFor Each Example

Dim lab As LabelDim lab As Label

For Each lab In thisForm.ControlsFor Each lab In thisForm.Controls

ComboBox1.Items.Add(lab.Text)ComboBox1.Items.Add(lab.Text)

NextNext

Page 19: Basic Concepts

File HandlingFile Handling

Page 20: Basic Concepts

OverviewOverview File handling is largely based on the File handling is largely based on the

System.IO System.IO namespace, which encloses a namespace, which encloses a class library that supports string, class library that supports string, character, and file manipulation.character, and file manipulation.

These classes include properties, These classes include properties, methods, and events for creating, methods, and events for creating, copying, moving, and deleting files.copying, moving, and deleting files.

The most commonly used classes are The most commonly used classes are FileStreamFileStream,, BinaryReader BinaryReader,, BinaryWriterBinaryWriter,, StreamReader StreamReader,, and and Streamwriter Streamwriter class.class.

Page 21: Basic Concepts

Reading FileReading File To read a line from a file with a text readerTo read a line from a file with a text reader

Dim fileReader As System.IO.StreamReaderDim fileReader As System.IO.StreamReader

fileReader = _fileReader = _

My.Computer.FileSystem.OpenTextFileReader("My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")C:\\testfile.txt")

Dim stringReader As StringDim stringReader As String

stringReader = fileReader.ReadLine()stringReader = fileReader.ReadLine()

MsgBox("The first line of the file is " & MsgBox("The first line of the file is " & stringReader)stringReader)

Page 22: Basic Concepts

Writing FileWriting File

Sub Main()Sub Main()

Dim s As StringDim s As String

s = Console.ReadLines = Console.ReadLine

Dim file As System.IO.StreamWriterDim file As System.IO.StreamWriter

file = file = My.Computer.FileSystem.OpenTextFileWriter("c:\My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)test.txt", True)

file.WriteLine(s)file.WriteLine(s)

file.Close()file.Close()

End SubEnd Sub

Page 23: Basic Concepts

Dialog BoxesDialog Boxes

Page 24: Basic Concepts

Dialog Boxes OverviewDialog Boxes Overview Dialog boxes are used to interact with the user and Dialog boxes are used to interact with the user and

retrieve information.retrieve information. In simple terms, a dialog box is a form with its In simple terms, a dialog box is a form with its

FormBorderStyle enumeration property set to FormBorderStyle enumeration property set to FixedDialogFixedDialog..

You can construct your own custom dialog boxes by You can construct your own custom dialog boxes by using the Windows Forms Designer in Visual Studio. using the Windows Forms Designer in Visual Studio. Add controls such as Add controls such as LabelLabel, , TextboxTextbox, and , and ButtonButton to customize dialog boxes to your specific needs.to customize dialog boxes to your specific needs.

The .NET Framework also includes predefined The .NET Framework also includes predefined dialog boxes, such as dialog boxes, such as File OpenFile Open and message boxes, and message boxes, which you can adapt for your own applications .which you can adapt for your own applications .

Page 25: Basic Concepts

Color Dialog BoxColor Dialog Box The Windows Forms ColorDialog component is a The Windows Forms ColorDialog component is a

pre-configured dialog box that allows the user to pre-configured dialog box that allows the user to select a color from a palette and to add custom select a color from a palette and to add custom colors to that palette. It is the same dialog box colors to that palette. It is the same dialog box that you see in other Windows-based applications that you see in other Windows-based applications to select colors. to select colors.

The color selected in the dialog box is returned The color selected in the dialog box is returned in the Color property.in the Color property.

If the AllowFullOpen property is set to If the AllowFullOpen property is set to falsefalse, the , the "Define Custom Colors" button is disabled and "Define Custom Colors" button is disabled and the user is restricted to the predefined colors in the user is restricted to the predefined colors in the palette. the palette.

If the SolidColorOnly property is set to If the SolidColorOnly property is set to truetrue, the , the user cannot select dithered colors. To display the user cannot select dithered colors. To display the dialog box, you must call its ShowDialog method. dialog box, you must call its ShowDialog method.

Page 26: Basic Concepts

Creating Color DialogsCreating Color DialogsPrivate Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.ClickIf ColorDialog1.ShowDialog( ) <> If ColorDialog1.ShowDialog( ) <>

DialogResult.Cancel ThenDialogResult.Cancel Then Label1.Text = “Here’s my new color !”Label1.Text = “Here’s my new color !” Label1.BackColor = ColorDialg1.ColorLabel1.BackColor = ColorDialg1.ColorEnd IfEnd If

End SubEnd Sub

Page 27: Basic Concepts

Font Dialog BoxFont Dialog Box The Windows Forms FontDialog component is a pre-The Windows Forms FontDialog component is a pre-

configured dialog box, which is the standard Windows configured dialog box, which is the standard Windows FontFont dialog box used to expose the fonts that are dialog box used to expose the fonts that are currently installed on the system. Use it within your currently installed on the system. Use it within your Windows-based application as a simple solution for Windows-based application as a simple solution for font selection in lieu of configuring your own dialog font selection in lieu of configuring your own dialog box.box.

By default, the dialog box shows list boxes for Font, By default, the dialog box shows list boxes for Font, Font style, and Size; check boxes for effects like Font style, and Size; check boxes for effects like Strikeout and Underline; a drop-down list for Script; Strikeout and Underline; a drop-down list for Script; and a sample of how the font will appear. (Script and a sample of how the font will appear. (Script refers to different character scripts that are available refers to different character scripts that are available for a given font, for example, Hebrew or Japanese.) for a given font, for example, Hebrew or Japanese.) To display the font dialog box, call the ShowDialog To display the font dialog box, call the ShowDialog method. method.

Page 28: Basic Concepts

Creating Font DialogsCreating Font DialogsPrivate Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.ClickIf FontDialog1.ShowDialog( ) <> If FontDialog1.ShowDialog( ) <>

DialogResult.Cancel ThenDialogResult.Cancel Then RichTextBox1.Font = FontDialog1.FontRichTextBox1.Font = FontDialog1.Font RichTextBox1.ForeColor = RichTextBox1.ForeColor =

FontDialog1.ColorFontDialog1.ColorEnd IfEnd If

End SubEnd Sub

Page 29: Basic Concepts

Save File Dialog BoxSave File Dialog Box

The Windows Forms SaveFileDialog The Windows Forms SaveFileDialog component is a pre-configured dialog box. It component is a pre-configured dialog box. It is the same as the standard Save File dialog is the same as the standard Save File dialog box used by Windows. It inherits from the box used by Windows. It inherits from the CommonDialog class. CommonDialog class.

Use it as a simple solution for enabling Use it as a simple solution for enabling users to save files instead of configuring users to save files instead of configuring your own dialog box. By relying on standard your own dialog box. By relying on standard Windows dialog boxes, the basic Windows dialog boxes, the basic functionality of applications you create is functionality of applications you create is immediately familiar to users. immediately familiar to users.

Page 30: Basic Concepts

Creating Save File Creating Save File DialogsDialogs

Private Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

If SaveFileDialog1.ShowDialog( ) <> If SaveFileDialog1.ShowDialog( ) <> DialogResult.Cancel ThenDialogResult.Cancel Then

MsgBox(“You chose ” & MsgBox(“You chose ” & SaveFileDialog1.FileNameSaveFileDialog1.FileName))

End IfEnd IfEnd SubEnd Sub

Page 31: Basic Concepts

Open File Dialog BoxOpen File Dialog Box The Windows Forms OpenFileDialog component is a The Windows Forms OpenFileDialog component is a

pre-configured dialog box. It is the same pre-configured dialog box. It is the same Open FileOpen File dialog box exposed by the Windows operating dialog box exposed by the Windows operating system. It inherits from the CommonDialog class. system. It inherits from the CommonDialog class.

Use the ShowDialog method to display the dialog at Use the ShowDialog method to display the dialog at run time. You can enable users to multi-select files run time. You can enable users to multi-select files to be opened with the Multiselect property. to be opened with the Multiselect property. Additionally, you can use the ShowReadOnly Additionally, you can use the ShowReadOnly property to determine if a read-only check box property to determine if a read-only check box appears in the dialog box. The ReadOnlyChecked appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only check box property indicates whether the read-only check box is selected. Finally, the Filter property sets the is selected. Finally, the Filter property sets the current file name filter string, which determines the current file name filter string, which determines the choices that appear in the "Files of type" box in the choices that appear in the "Files of type" box in the dialog box. dialog box.

Page 32: Basic Concepts

Creating Open File Creating Open File DialogsDialogs

Private Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

If OpenFileDialog1.ShowDialog( ) <> If OpenFileDialog1.ShowDialog( ) <> DialogResult.Cancel ThenDialogResult.Cancel Then

PictureBox1.Image = _PictureBox1.Image = _

Image.FromFile(Image.FromFile(OpenFileDialog1.FileNameOpenFileDialog1.FileName))

End IfEnd If

End SubEnd Sub

Page 33: Basic Concepts

Exception Exception HandlingHandling

Page 34: Basic Concepts

Exception Handling Exception Handling OverviewOverview

Visual Basic supports structured Visual Basic supports structured exception (error) handling, which exception (error) handling, which allows the program to detect and allows the program to detect and possibly recover from errors during possibly recover from errors during execution.execution.

Visual Basic uses an enhanced Visual Basic uses an enhanced version of the version of the Try...Catch...FinallyTry...Catch...Finally syntax already supported by other syntax already supported by other languages such as C++. languages such as C++.

Page 35: Basic Concepts

Structured Exception Structured Exception HandlingHandling

Structured exception handling Structured exception handling combines a modern control structure combines a modern control structure (similar to (similar to Select CaseSelect Case or or WhileWhile) ) with exceptions, protected blocks of with exceptions, protected blocks of code, and filters.code, and filters.

Structured exception handling, which Structured exception handling, which is the recommended method of error is the recommended method of error handling in Visual Basic, makes it easy handling in Visual Basic, makes it easy to create and maintain programs with to create and maintain programs with robust, comprehensive error handlers. robust, comprehensive error handlers.

Page 36: Basic Concepts

Unstructured Exception Unstructured Exception HandlingHandling

Unstructured exception handling Unstructured exception handling using using On ErrorOn Error can degrade can degrade application performance and result application performance and result in code that is difficult to debug and in code that is difficult to debug and maintain. maintain.

Page 37: Basic Concepts

Try-catchTry-catch

Place the sections of code that might Place the sections of code that might throw exceptions in a try block and throw exceptions in a try block and place code that handles exceptions place code that handles exceptions in a catch block.in a catch block.

The catch block is a series of The catch block is a series of statements beginning with the statements beginning with the keyword keyword catchcatch, followed by an , followed by an exception type and an action to be exception type and an action to be taken.taken.

Page 38: Basic Concepts

Try-catch ExampleTry-catch Example

Dim Top As Double = 5Dim Top As Double = 5Dim Bottom As Double = 0Dim Bottom As Double = 0Dim Result As IntegerDim Result As IntegerTryTry Result = CType(Top / Bottom, Integer)Result = CType(Top / Bottom, Integer)Catch Exc As System.OverflowExceptionCatch Exc As System.OverflowException MsgBox("Attempt to divide by zero MsgBox("Attempt to divide by zero

resulted in overflow")resulted in overflow")End TryEnd Try

Page 39: Basic Concepts

Try with multiple catchTry with multiple catchTryTry ' Add code for your I/O task here. ' Add code for your I/O task here. Catch dirNotFound As System.IO.DirectoryNotFoundExceptionCatch dirNotFound As System.IO.DirectoryNotFoundException Throw dirNotFoundThrow dirNotFoundCatch fileNotFound As System.IO.FileNotFoundExceptionCatch fileNotFound As System.IO.FileNotFoundException Throw fileNotFoundThrow fileNotFoundCatch pathTooLong As System.IO.PathTooLongExceptionCatch pathTooLong As System.IO.PathTooLongException Throw pathTooLongThrow pathTooLongCatch ioEx As System.IO.IOExceptionCatch ioEx As System.IO.IOException Throw ioExThrow ioExCatch security As System.Security.SecurityExceptionCatch security As System.Security.SecurityException Throw securityThrow securityCatch ex As ExceptionCatch ex As Exception Throw exThrow exEnd TryEnd Try

Page 40: Basic Concepts

Try-catch FinallyTry-catch Finally A A FinallyFinally statement can be used statement can be used

within a within a TryTry block to ensure allocated block to ensure allocated resources are clean. The code in a resources are clean. The code in a FinallyFinally block runs after the exception- block runs after the exception-handling code, but before control handling code, but before control returns to the calling procedure. The returns to the calling procedure. The code in a code in a FinallyFinally block will run even if block will run even if your code throws an exception, and your code throws an exception, and even if you add an explicit even if you add an explicit Exit Exit FunctionFunction (or (or Exit SubExit Sub) statement ) statement within a within a CatchCatch block block

Page 41: Basic Concepts

Continued…Continued… Example:Example:

Public Sub TryExample()Public Sub TryExample() Dim x As Double = 5 ' Declare variables.Dim x As Double = 5 ' Declare variables. Dim y As Integer = 0Dim y As Integer = 0 Try ' Set up structured error handling.Try ' Set up structured error handling. x /= y ' Cause a "Divide by Zero" error.x /= y ' Cause a "Divide by Zero" error. Catch ex As Exception When y = 0 ' Catch the Catch ex As Exception When y = 0 ' Catch the

error.error. MsgBox(ex.ToString) ' Show friendly error MsgBox(ex.ToString) ' Show friendly error

message.message. FinallyFinally Beep() ' This line is executed no matter what.Beep() ' This line is executed no matter what. End TryEnd Try

End SubEnd Sub

Page 42: Basic Concepts

On Error Resume NextOn Error Resume Next On Error Resume NextOn Error Resume Next causes execution to causes execution to

continue with the statement immediately following continue with the statement immediately following the statement that caused the run-time error, or with the statement that caused the run-time error, or with the statement immediately following the most recent the statement immediately following the most recent call out of the procedure containing the call out of the procedure containing the On Error On Error Resume NextResume Next statement. statement.

This statement allows execution to continue despite This statement allows execution to continue despite a run-time error.a run-time error.

You can place the error-handling routine where the You can place the error-handling routine where the error would occur rather than transferring control to error would occur rather than transferring control to another location within the procedure. An another location within the procedure. An On Error On Error Resume NextResume Next statement becomes inactive when statement becomes inactive when another procedure is called, so you should execute another procedure is called, so you should execute an an On Error Resume NextOn Error Resume Next statement in each called statement in each called routine if you want inline error handling within that routine if you want inline error handling within that routine.routine.

Page 43: Basic Concepts

ExampleExampleSub ResumeStatementDemo()Sub ResumeStatementDemo() On Error GoTo ErrorHandler ' Enable error-handling routine.On Error GoTo ErrorHandler ' Enable error-handling routine. Dim x As Integer = 32Dim x As Integer = 32 Dim y As Integer = 0Dim y As Integer = 0 Dim z As IntegerDim z As Integer z = x / y ' Creates a divide by zero errorz = x / y ' Creates a divide by zero error

Exit Sub ' Exit Sub to avoid error handler.Exit Sub ' Exit Sub to avoid error handler.ErrorHandler: ' Error-handling routine.ErrorHandler: ' Error-handling routine.

Select Case Err.Number ' Evaluate error number.Select Case Err.Number ' Evaluate error number. Case 6 ' "Divide by zero" error.’Case 6 ' "Divide by zero" error.’ y = 1 ' Sets the value of y to 1 and tries the y = 1 ' Sets the value of y to 1 and tries the

calculation again.calculation again. Case ElseCase Else ' Handle other situations here....' Handle other situations here.... End SelectEnd Select Resume ' Resume execution at same line that caused the Resume ' Resume execution at same line that caused the

error.error.End SubEnd Sub

Page 44: Basic Concepts

On Error GotoOn Error Goto GoToGoTo lineline

Enables the error-handling routine that starts at the Enables the error-handling routine that starts at the line specified in the required line specified in the required lineline argument. The argument. The lineline argument is any line label or line number. If a run-time argument is any line label or line number. If a run-time error occurs, control branches to the specified line, error occurs, control branches to the specified line, making the error handler active. The specified line must making the error handler active. The specified line must be in the same procedure as the be in the same procedure as the On ErrorOn Error statement, statement, or a compile-time error will occur.or a compile-time error will occur.

GoToGoTo 0 0 Disables enabled error handler in the current Disables enabled error handler in the current

procedure and resets it to procedure and resets it to NothingNothing..

GoToGoTo -1 -1 Disables enabled exception in the current procedure Disables enabled exception in the current procedure

and resets it to and resets it to NothingNothing..

Page 45: Basic Concepts

ExampleExamplePublic Sub OnErrorDemo()Public Sub OnErrorDemo() On Error GoTo ErrorHandler ' Enable error-handling routine.On Error GoTo ErrorHandler ' Enable error-handling routine. Dim x As Integer = 32Dim x As Integer = 32 Dim y As Integer = 0Dim y As Integer = 0 Dim z As IntegerDim z As Integer z = x / y ' Creates a divide by zero errorz = x / y ' Creates a divide by zero error On Error GoTo 0 ' Turn off error trapping.On Error GoTo 0 ' Turn off error trapping. On Error Resume Next ' Defer error trapping.On Error Resume Next ' Defer error trapping. z = x / y ' Creates a divide by zero error againz = x / y ' Creates a divide by zero error again If Err.Number = 6 ThenIf Err.Number = 6 Then ' Tell user what happened. Then clear the Err object.' Tell user what happened. Then clear the Err object. Dim Msg As StringDim Msg As String Msg = "There was an error attempting to divide by zero!"Msg = "There was an error attempting to divide by zero!" MsgBox(Msg, , "Divide by zero error")MsgBox(Msg, , "Divide by zero error") Err.Clear() ' Clear Err object fields.Err.Clear() ' Clear Err object fields. End IfEnd If Exit Sub ' Exit to avoid handler.Exit Sub ' Exit to avoid handler.

Page 46: Basic Concepts

Continued…Continued…ErrorHandler: ' Error-handling routine.ErrorHandler: ' Error-handling routine.

Select Case Err.Number ' Evaluate error number.Select Case Err.Number ' Evaluate error number. Case 6 ' Divide by zero errorCase 6 ' Divide by zero error MsgBox("You attempted to divide by MsgBox("You attempted to divide by

zero!")zero!") ' Insert code to handle this error' Insert code to handle this error Case ElseCase Else ' Insert code to handle other situations ' Insert code to handle other situations

here...here... End SelectEnd Select Resume Next ' Resume execution at same line that Resume Next ' Resume execution at same line that

caused the error.caused the error.End SubEnd Sub

Page 47: Basic Concepts

Types of ExceptionsTypes of Exceptions In Visual Basic, errors (also called In Visual Basic, errors (also called exceptionsexceptions) )

fall into one of three categories: syntax errors, fall into one of three categories: syntax errors, run-time errors, and logic errors.run-time errors, and logic errors.

Syntax Errors: Syntax Errors: Syntax errorsSyntax errors are those that are those that appear while you write code. Visual Basic checks appear while you write code. Visual Basic checks your code as you type it in the your code as you type it in the Code EditorCode Editor window and alerts you if you make a mistake, window and alerts you if you make a mistake, such as misspelling a word or using a language such as misspelling a word or using a language element improperly. Syntax errors are the most element improperly. Syntax errors are the most common type of errors. You can fix them easily in common type of errors. You can fix them easily in the coding environment as soon as they occur.the coding environment as soon as they occur.

Page 48: Basic Concepts

Continued…Continued… Run-time Errors: Run-time Errors: Run-time errorsRun-time errors are those that are those that

appear only after you compile and run your code. appear only after you compile and run your code. These involve code that may appear to be correct These involve code that may appear to be correct in that it has no syntax errors, but that will not in that it has no syntax errors, but that will not execute. For example, you might correctly write execute. For example, you might correctly write a line of code to open a file. But if the file is a line of code to open a file. But if the file is corrupted, the application cannot carry out the corrupted, the application cannot carry out the OpenOpen function, and it stops running. You can fix function, and it stops running. You can fix most run-time errors by rewriting the faulty most run-time errors by rewriting the faulty code, and then recompiling and rerunning it.code, and then recompiling and rerunning it.

Page 49: Basic Concepts

Continued…Continued… Logic Errors: Logic Errors: Logic errorsLogic errors are those that appear are those that appear

once the application is in use. They are most once the application is in use. They are most often unwanted or unexpected results in often unwanted or unexpected results in response to user actions. For example, a response to user actions. For example, a mistyped key or other outside influence might mistyped key or other outside influence might cause your application to stop working within cause your application to stop working within expected parameters, or altogether. Logic errors expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is are generally the hardest type to fix, since it is not always clear where they originate.not always clear where they originate.

Page 50: Basic Concepts

OthersOthers

Standard Exception : Standard Exception : Represents Represents errors that occur during application errors that occur during application execution.execution.

Application Exception Class : Application Exception Class : The The exception that is thrown when a non-exception that is thrown when a non-fatal application error occurs. fatal application error occurs.

System Exception Class : System Exception Class : Defines Defines the base class for predefined the base class for predefined exceptions in the System namespace. exceptions in the System namespace.

Page 51: Basic Concepts

MenusMenus

Page 52: Basic Concepts

OverviewOverview

Menus are those controls that allow the user Menus are those controls that allow the user to make selections and also hide away those to make selections and also hide away those selections when they are not needed, saving selections when they are not needed, saving space in Windows application.space in Windows application.

Menu Items : Menu Items : Menus like File and Edit and Menus like File and Edit and the actual items in such menus are the actual items in such menus are supported with the supported with the MenuItem MenuItem class. This class. This class supports the actual controls in your class supports the actual controls in your menu system, and its their menu system, and its their Click Click event that event that you add code to in order to make that menu you add code to in order to make that menu system active. system active.

Page 53: Basic Concepts

Types of MenuTypes of Menu

Standard Menu : Standard Menu : The most The most common type of menu.common type of menu.

Context Menu : Context Menu : Commonly known Commonly known as Pop-up menu.as Pop-up menu.

Page 54: Basic Concepts

Main MenuMain Menu

The The MainMenu MainMenu control represents the control represents the container for the menu structure of a container for the menu structure of a form; you can assign a control of this form; you can assign a control of this type to a form’s type to a form’s Menu Menu property at run-property at run-time.time.

Menus are made up of Menus are made up of MenuItem MenuItem objects that represent the individual objects that represent the individual parts of a menu.parts of a menu.

Menu items can be a parent menu or a Menu items can be a parent menu or a menu item in a main menumenu item in a main menu

Page 55: Basic Concepts

OverviewOverview Structured programmingStructured programming is an approach that is an approach that

emphasizes program modularity and a emphasizes program modularity and a hierarchical structure within an application.hierarchical structure within an application.

In Visual Basic, the most straightforward way In Visual Basic, the most straightforward way to achieve structured programming is to achieve structured programming is through judicious use of functions and through judicious use of functions and procedures to break your application into procedures to break your application into discrete logical units. You can debug each discrete logical units. You can debug each individual unit more easily than the entire individual unit more easily than the entire program. You can also use a procedure program. You can also use a procedure developed for one program in other developed for one program in other programs, often with little or no modification.programs, often with little or no modification.

Page 56: Basic Concepts

Functions & Functions & ProceduresProcedures

Page 57: Basic Concepts

CreatingCreating Declaration : Declaration :

[<attributelist>] [{ Overloads | Overrides | [<attributelist>] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverridable | Shadows | Overridable | NotOverridable | MustOverridable | Shadows | Shared }] [{accessmodifier}] Function-name [(arglist)] [As Shared }] [{accessmodifier}] Function-name [(arglist)] [As type] type] [Implements interface.definedname][Implements interface.definedname]

[ statements ][ statements ][ Exit Function ][ Exit Function ][ statements ][ statements ]

End functionEnd function

Example : Example : function Add (ByVal int1 as Integer, ByVal int2 as Integer) As function Add (ByVal int1 as Integer, ByVal int2 as Integer) As LongLong

Return int1 * int2Return int1 * int2End FunctionEnd Function

Page 58: Basic Concepts

Types of ProceduresTypes of Procedures Visual Basic uses several types of procedures:Visual Basic uses several types of procedures: Sub ProceduresSub Procedures perform actions but do not return a perform actions but do not return a

value to the calling code.value to the calling code. Event-handling ProceduresEvent-handling Procedures are are SubSub procedures that procedures that

execute in response to an event raised by user action execute in response to an event raised by user action or by an occurrence in a program.or by an occurrence in a program.

Function ProceduresFunction Procedures return a value to the calling return a value to the calling code. They can perform other actions before returning.code. They can perform other actions before returning.

Property ProceduresProperty Procedures return and assign values of return and assign values of properties on objects or modules.properties on objects or modules.

Operator ProceduresOperator Procedures define the behavior of a define the behavior of a standard operator when one or both of the operands is standard operator when one or both of the operands is a newly-defined class or structure.a newly-defined class or structure.

Generic ProceduresGeneric Procedures in Visual Basic define one or in Visual Basic define one or more more type parameterstype parameters in addition to their normal in addition to their normal parameters, so the calling code can pass specific data parameters, so the calling code can pass specific data types each time it makes a call.types each time it makes a call.

Page 59: Basic Concepts

Sub ProceduresSub Procedures A A SubSub procedure is a series of Visual Basic procedure is a series of Visual Basic

statements enclosed by the statements enclosed by the SubSub and and End SubEnd Sub statements. The statements. The SubSub procedure performs a task and procedure performs a task and then returns control to the calling code, but it does then returns control to the calling code, but it does not return a value to the calling code.not return a value to the calling code.

Each time the procedure is called, its statements are Each time the procedure is called, its statements are executed, starting with the first executable statement executed, starting with the first executable statement after the after the SubSub statement and ending with the first statement and ending with the first End End SubSub, , Exit SubExit Sub, or , or ReturnReturn statement encountered. statement encountered.

When you use When you use ByVal ByVal (the default in VB.Net), you pass (the default in VB.Net), you pass a copy of a variable to a procedure; when you use a copy of a variable to a procedure; when you use ByRefByRef, you pass a reference to the variable, and if , you pass a reference to the variable, and if you make changes to that reference, the original you make changes to that reference, the original variable is changed.variable is changed.

Page 60: Basic Concepts

Creating a Sub Creating a Sub ProcedureProcedure

Declaration : Declaration : [<attributelist>] [{ Overloads | Overrides | [<attributelist>] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverridable | Shadows | Overridable | NotOverridable | MustOverridable | Shadows | Shared }] [{accessmodifier}] Sub-name [(arglist)] [As type] Shared }] [{accessmodifier}] Sub-name [(arglist)] [As type] [Implements interface.definedname][Implements interface.definedname]

[ statements ][ statements ][ Exit Function ][ Exit Function ][ statements ][ statements ]

End subEnd sub Example : Example :

Module Module1Module Module1Sub Main ( )Sub Main ( )

DisplayMsg( “Hello” )DisplayMsg( “Hello” )End SubEnd Sub

Sub DisplayMsg(ByVal strText As String)Sub DisplayMsg(ByVal strText As String)System.Console.WriteLine( strText)System.Console.WriteLine( strText)

End SubEnd SubEnd ModuleEnd Module

Page 61: Basic Concepts

Calling Sub ProceduresCalling Sub Procedures

Syntax : call Syntax : call procedure-procedure-name(argument-list)name(argument-list)

Example : Example : Call Call DisplayMsg( “Hello” )DisplayMsg( “Hello” )

Page 62: Basic Concepts

Function ProceduresFunction Procedures A A FunctionFunction procedure is a series of Visual procedure is a series of Visual

Basic statements enclosed by the Basic statements enclosed by the FunctionFunction and and End FunctionEnd Function statements. The statements. The FunctionFunction procedure performs a task and then returns procedure performs a task and then returns control to the calling code. When it returns control to the calling code. When it returns control, it also returns a value to the calling control, it also returns a value to the calling code.code.

Each time the procedure is called, its Each time the procedure is called, its statements run, starting with the first statements run, starting with the first executable statement after the executable statement after the FunctionFunction statement and ending with the first statement and ending with the first End End FunctionFunction, , Exit FunctionExit Function, or , or ReturnReturn statement encountered.statement encountered.

Page 63: Basic Concepts

Creating Function Creating Function ProceduresProcedures

Declaration : Declaration : [<attributelist>] [<attributelist>] [{ Overloads | Overrides | Overridable | NotOverridable | [{ Overloads | Overrides | Overridable | NotOverridable | MustOverridable | Shadows | Shared }] [{accessmodifier}] MustOverridable | Shadows | Shared }] [{accessmodifier}] Function-name [(arglist)] [As type] Function-name [(arglist)] [As type] [Implements [Implements interface.definedname]interface.definedname]

[ statements ][ statements ][ Exit Function ][ Exit Function ][ statements ][ statements ]

End functionEnd function Example : Example :

Module Module1Module Module1Sub Main ( )Sub Main ( )

Dim intV As Integer = 2Dim intV As Integer = 2System.Console.WriteLine( “{0} + {1} = {2}”, _System.Console.WriteLine( “{0} + {1} = {2}”, _ intV, intV, Add( intV, intV ) )intV, intV, Add( intV, intV ) )

End SubEnd SubFunction Add( ByVal int1 As Integer, ByVal int2 As Integer )Function Add( ByVal int1 As Integer, ByVal int2 As Integer )

Return int1 + int2Return int1 + int2End SubEnd Sub

End ModuleEnd Module

Page 64: Basic Concepts

Calling Function Calling Function ProceduresProcedures

Syntax : call Syntax : call function-function-name(argument-list)name(argument-list)

Example : Example : Call tellOperator(intV, Call tellOperator(intV, intV)intV)

Page 65: Basic Concepts

ParameterizedParameterized A A parameterparameter represents a value that the procedure represents a value that the procedure

expects you to pass when you call it. The expects you to pass when you call it. The procedure's declaration defines its parameters.procedure's declaration defines its parameters.

When you define a When you define a FunctionFunction or or SubSub procedure, you procedure, you specify a specify a parameter listparameter list in parentheses immediately in parentheses immediately following the procedure name. For each parameter, following the procedure name. For each parameter, you specify a name, a data type, and a passing you specify a name, a data type, and a passing mechanism (ByVal or ByRef). You can also indicate mechanism (ByVal or ByRef). You can also indicate that a parameter is optional, meaning the calling that a parameter is optional, meaning the calling code does not have to pass a value for it.code does not have to pass a value for it.

The name of each parameter serves as a The name of each parameter serves as a local local variablevariable within the procedure. You use the within the procedure. You use the parameter name the same way you use any other parameter name the same way you use any other variable.variable.

Page 66: Basic Concepts

Example Example The following example defines the outline of a The following example defines the outline of a

SubSub procedure with three parameters. The first procedure with three parameters. The first two are required and the third is optional. The two are required and the third is optional. The parameter declarations are separated in the parameter declarations are separated in the parameter list by commas.parameter list by commas.

Sub updateCustomer(ByRef c As customer, ByVal Sub updateCustomer(ByRef c As customer, ByVal region As String, _region As String, _

Optional ByVal level As Integer = 0)Optional ByVal level As Integer = 0) ' Insert code to update a customer object.' Insert code to update a customer object.End SubEnd Sub

Page 67: Basic Concepts

Non ParameterizedNon Parameterized

That don’t contain any parameters.That don’t contain any parameters. Example:Example:

Function myFunction( ) As DoubleFunction myFunction( ) As Double

Return 3.87 * 2Return 3.87 * 2

End FunctionEnd Function

Page 68: Basic Concepts

Module OverviewModule Overview A loadable unit, which can contain type A loadable unit, which can contain type

declarations and type implementations. declarations and type implementations. The module contains enough The module contains enough information to enable the common information to enable the common language runtime to locate all language runtime to locate all implementation bits when the module is implementation bits when the module is loaded. The format for modules is an loaded. The format for modules is an extension of the Windows portable extension of the Windows portable executable (PE) file format. When executable (PE) file format. When deployed, a module is always contained deployed, a module is always contained in an assembly. in an assembly.

Page 69: Basic Concepts

Creating a ModuleCreating a Module

Public Module thisModulePublic Module thisModule

Sub Main()Sub Main()

Dim userName As String = InputBox("What is your Dim userName As String = InputBox("What is your name?")name?")

MsgBox("User name is" & userName)MsgBox("User name is" & userName)

End SubEnd Sub

' Insert variable, property, procedure, and event ' Insert variable, property, procedure, and event declarations.declarations.

End ModuleEnd Module

Page 70: Basic Concepts

Array, Structure Array, Structure & Collections& Collections

Page 71: Basic Concepts

Single Dimension ArraySingle Dimension Array

In your declaration, add one pair of In your declaration, add one pair of parentheses after the variable name. parentheses after the variable name. The following example declares a The following example declares a variable to hold a one-dimensional variable to hold a one-dimensional array with elements of the Double array with elements of the Double Data Type:Data Type:

Dim cargoWeights() As DoubleDim cargoWeights() As Double

Page 72: Basic Concepts

Multi Dimension ArrayMulti Dimension Array

In your declaration, add one pair of In your declaration, add one pair of parentheses after the variable name parentheses after the variable name and place commas inside the and place commas inside the parentheses to separate the dimensions. parentheses to separate the dimensions. The following example declares a The following example declares a variable to hold a four-dimensional variable to hold a four-dimensional array with elements of the Short Data array with elements of the Short Data Type:Type:

Dim atmospherePressures( , , , ) As Dim atmospherePressures( , , , ) As ShortShort

Page 73: Basic Concepts

ExamplesExamples

Dim validDates() As Date = New Dim validDates() As Date = New Date() {}Date() {}

Dim oneDimension(), Dim oneDimension(), twoDimensions(,), twoDimensions(,), threeDimensions(,,) As BytethreeDimensions(,,) As Byte

Page 74: Basic Concepts

Examples- Multi Dimension Examples- Multi Dimension ArrayArray

Dim matrix(9, 9) As DoubleDim matrix(9, 9) As Double

Dim maxDim0 As Integer = UBound(matrix, 1)Dim maxDim0 As Integer = UBound(matrix, 1)

Dim maxDim1 As Integer = UBound(matrix, 2)Dim maxDim1 As Integer = UBound(matrix, 2)

For i As Integer = 0 To maxDim0For i As Integer = 0 To maxDim0

For j As Integer = 0 To maxDim1For j As Integer = 0 To maxDim1

matrix(i, j) = (i * 10) + jmatrix(i, j) = (i * 10) + j

Next jNext j

Next iNext i

Page 75: Basic Concepts

StructureStructure Holds data in a format you define. The Holds data in a format you define. The

StructureStructure statement defines the format. statement defines the format. Define and use a structure data type Define and use a structure data type

when you need to combine various data when you need to combine various data types into a single unit, or when none of types into a single unit, or when none of the elementary data types serve your the elementary data types serve your needs.needs.

The default value of a structure data The default value of a structure data type consists of the combination of the type consists of the combination of the default values of each of its members.default values of each of its members.

Page 76: Basic Concepts

Creating a StructureCreating a Structure Syntax : Syntax :

structure structure-namestructure structure-name

//Member declarations//Member declarations

End StructureEnd Structure Example : Example :

Structure EmployeeStructure Employee

Public EmpNumber As Integer 'Must declare Public EmpNumber As Integer 'Must declare access, even if Public. access, even if Public.

Dim EmpOffPhone As String 'Still defaults to Dim EmpOffPhone As String 'Still defaults to Public access. Public access.

Private EmpHPhone As String 'Can be made Private EmpHPhone As String 'Can be made Private inside Structure. Private inside Structure.

End StructureEnd Structure

Page 77: Basic Concepts

Collections Collections Closely related data can be handled more Closely related data can be handled more

efficiently when grouped together into a efficiently when grouped together into a collection. Instead of writing separate collection. Instead of writing separate code to handle each individual object, you code to handle each individual object, you can use the same code to process all the can use the same code to process all the elements of a collection.elements of a collection.

To manage a collection, the Array class To manage a collection, the Array class and the System.Collections classes are and the System.Collections classes are used to add, remove, and modify either used to add, remove, and modify either individual elements of the collection or a individual elements of the collection or a range of elements. An entire collection range of elements. An entire collection can even be copied to another collection.can even be copied to another collection.

Page 78: Basic Concepts

ArraylistArraylist An ArrayList or List object is a sophisticated version of an An ArrayList or List object is a sophisticated version of an

array. The array. The ArrayListArrayList class and the class and the ListList generic class generic class provides some features that are offered in most provides some features that are offered in most System.Collections classes but are not in the Array class. System.Collections classes but are not in the Array class. For example: For example:

The capacity of an The capacity of an ArrayArray is fixed, whereas the capacity of is fixed, whereas the capacity of an an ArrayListArrayList or a or a ListList is automatically expanded as is automatically expanded as required. If the value of the required. If the value of the CapacityCapacity property is changed, property is changed, the memory reallocation and copying of elements are the memory reallocation and copying of elements are automatically done.automatically done.

ArrayListArrayList and and ListList provide methods that add, insert, or provide methods that add, insert, or remove a range of elements. In remove a range of elements. In ArrayArray, you can get or set , you can get or set the value of only one element at a time.the value of only one element at a time.

A synchronized version of A synchronized version of ArrayListArrayList or or ListList is easy to is easy to create using the create using the SynchronizedSynchronized method. The method. The ArrayArray class class leaves it up to the user to implement synchronization.leaves it up to the user to implement synchronization.

ArrayListArrayList and and ListList provide methods that return read-only provide methods that return read-only and fixed-size wrappers to the collection. and fixed-size wrappers to the collection. ArrayArray does not. does not.

Page 79: Basic Concepts

StackStack The Stack class and the Stack generic class are last-in-first-The Stack class and the Stack generic class are last-in-first-

out collection classes that implement the ICollection out collection classes that implement the ICollection interface. The interface. The StackStack generic class also implements the generic class also implements the ICollection generic interface.ICollection generic interface.

Stacks and queues are useful when you need temporary Stacks and queues are useful when you need temporary storage for information, that is, when you might want to storage for information, that is, when you might want to discard an element after retrieving its value. Use discard an element after retrieving its value. Use QueueQueue if if you need to access the information in the same order that it is you need to access the information in the same order that it is stored in the collection. Use stored in the collection. Use StackStack if you need to access the if you need to access the information in reverse order.information in reverse order.

A common use for a A common use for a StackStack is preserving variable states is preserving variable states during calls to other procedures.during calls to other procedures.

Three main operations can be performed on a Three main operations can be performed on a StackStack and its and its elements: elements:

PushPush inserts an element at the top of the inserts an element at the top of the Stack.Stack. PopPop removes an element at the top of the removes an element at the top of the StackStack.. PeekPeek returns an element at the top of the returns an element at the top of the StackStack but does not but does not

remove it from the remove it from the StackStack..

Page 80: Basic Concepts

QueueQueue The Queue class and the Queue generic class are first-in-The Queue class and the Queue generic class are first-in-

first-out collection classes that implement the ICollection first-out collection classes that implement the ICollection interface and the ICollection generic interface.interface and the ICollection generic interface.

The The QueueQueue and Stack classes, and the and Stack classes, and the QueueQueue and Stack and Stack generic classes are useful when you need temporary generic classes are useful when you need temporary storage for information, that is, when you might want to storage for information, that is, when you might want to discard an element after retrieving its value. Use discard an element after retrieving its value. Use QueueQueue if if you need to access the information in the same order that it you need to access the information in the same order that it is stored in the collection. Use is stored in the collection. Use StackStack if you need to access if you need to access the information in reverse order.the information in reverse order.

Three main operations can be performed on a Three main operations can be performed on a QueueQueue and and its elements: its elements:

EnqueueEnqueue adds an element to the end of the adds an element to the end of the QueueQueue.. DequeueDequeue removes the oldest element from the start of the removes the oldest element from the start of the

QueueQueue.. PeekPeek returns the oldest element from the start of the returns the oldest element from the start of the

QueueQueue but does not remove it from the but does not remove it from the QueueQueue..

Page 81: Basic Concepts

Object oriented Object oriented ProgrammingProgramming

Page 82: Basic Concepts

Creating ClassesCreating Classes Declaration : Declaration :

[<attributelist>] [accessmodifier] [<attributelist>] [accessmodifier] [Shadows] [MustInherit | NotInheritable] Class-name [Inherits [Shadows] [MustInherit | NotInheritable] Class-name [Inherits Class-name] [Implements Class-name]Class-name] [Implements Class-name][ statements ][ statements ]End ClassEnd Class

Example :Example :Public Class DataClassPublic Class DataClassPrivate value As Integer //Data MemberPrivate value As Integer //Data MemberPublic Sub New(ByVal newVal As Integer) //ConstructorPublic Sub New(ByVal newVal As Integer) //Constructorvalue = newValvalue = newValEnd SubEnd SubPublic Function GetData( ) As Integer //Member MethodPublic Function GetData( ) As Integer //Member MethodReturn valueReturn valueEnd FunctionEnd FunctionEnd ClassEnd Class

Page 83: Basic Concepts

Creating ObjectsCreating Objects Declaration : Declaration :

[<attributelist>] [accessmodifier] [Shadows] [<attributelist>] [accessmodifier] [Shadows] [ReadOnly] Dim [WithEvents] name [ReadOnly] Dim [WithEvents] name [ (boundlist) ] [ As [New] type ] [ = initexpr ][ (boundlist) ] [ As [New] type ] [ = initexpr ]

Example :Example :

Dim employee As New EmployeeClass()Dim employee As New EmployeeClass()

Dim employee As EmployeeClass = New Dim employee As EmployeeClass = New EmployeeClass()EmployeeClass()

Page 84: Basic Concepts

Inheritence Example-1Inheritence Example-1Public Class Form1Public Class Form1

Inherits System.Windows.Forms.Form //Form Designer Inherits System.Windows.Forms.Form //Form Designer generated codegenerated code

Dim spot As DogDim spot As Dog

Private Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

spot = New Dog( )spot = New Dog( )

spot.Breathing( )spot.Breathing( )

End SubEnd Sub

End ClassEnd Class

Public Class AnimalPublic Class Animal

Protected MainForm As Form1Protected MainForm As Form1

Public Sub New(ByVal form1) As Form1Public Sub New(ByVal form1) As Form1

MainForm = form1MainForm = form1

End SubEnd Sub

Page 85: Basic Concepts

Continued…Continued…Public Sub Breathing( )Public Sub Breathing( )

MainForm.TextBox1.Text = “Breathing….”MainForm.TextBox1.Text = “Breathing….”End SubEnd Sub

End ClassEnd Class

Public Class DogPublic Class DogInherits AnimalInherits Animal

Public Sub New(ByVal form1 As Form1)Public Sub New(ByVal form1 As Form1)MyBase.New(form1)MyBase.New(form1)

End SubEnd SubPublic Sub Barking( )Public Sub Barking( )

MainForm.TextBox1.Text = “Barking….”MainForm.TextBox1.Text = “Barking….”End SubEnd Sub

End ClassEnd Class

Page 86: Basic Concepts

Inheritence Inheritence Public Class Form1Public Class Form1

Inherits System.Windows.Forms.Form //Form Designer Inherits System.Windows.Forms.Form //Form Designer generated codegenerated code

Dim spot As DogDim spot As Dog

Dim jaws As FishDim jaws As Fish

Private Sub Button1_Click(ByVal) sender as System.Object,_Private Sub Button1_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

spot = New Dog( Me )spot = New Dog( Me )

spot.Breathing( )spot.Breathing( )

End SubEnd Sub

Private Sub Button2_Click(ByVal) sender as System.Object,_Private Sub Button2_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

jaws = New Fish( Me )jaws = New Fish( Me )

jaws.Breathing( )jaws.Breathing( )

End SubEnd Sub

End ClassEnd Class

Page 87: Basic Concepts

Continued…Continued…Public Class AnimalPublic Class Animal

Protected MainForm As Form1Protected MainForm As Form1Public Sub New(ByVal form1) As Form1Public Sub New(ByVal form1) As Form1

MainForm = form1MainForm = form1End SubEnd Sub

Public Overridable Sub Breathing( )Public Overridable Sub Breathing( )MainForm.TextBox1.Text = “Breathing….”MainForm.TextBox1.Text = “Breathing….”

End SubEnd SubEnd ClassEnd Class

Public Class DogPublic Class DogInherits AnimalInherits Animal

Public Sub New(ByVal form1 As Form1)Public Sub New(ByVal form1 As Form1)MyBase.New(form1)MyBase.New(form1)

End SubEnd Sub

Page 88: Basic Concepts

Continued…Continued…Public Sub Barking( )Public Sub Barking( )

MainForm.TextBox1.Text = “Barking….”MainForm.TextBox1.Text = “Barking….”End SubEnd Sub

End ClassEnd Class

Public Class FishPublic Class FishInherits AnimalInherits Animal

Public Sub New(ByVal form1 As Form1)Public Sub New(ByVal form1 As Form1)MyBase.New(form1)MyBase.New(form1)

End SubEnd Sub

Public Overrides Sub Breathing( )Public Overrides Sub Breathing( )MainForm.TextBox1.Text = “Bubbling….”MainForm.TextBox1.Text = “Bubbling….”

End SubEnd SubEnd ClassEnd Class

Page 89: Basic Concepts

Using Friend AccessUsing Friend Access Entities declared as Entities declared as FriendFriend have friend access. They are have friend access. They are

accessible from within the program that contains their accessible from within the program that contains their declaration and from anywhere else in the same assembly.declaration and from anywhere else in the same assembly.

Example :Example :Public Class DisplayerPublic Class Displayer

Friend Sub Display(ByVal Text As String)Friend Sub Display(ByVal Text As String)MsgBox(Text)MsgBox(Text)

End SubEnd SubEnd ClassEnd Class

Dim d As New Displayer()Dim d As New Displayer()Private Sub Button1_Click(ByVal) sender as Private Sub Button1_Click(ByVal) sender as System.Object,_System.Object,_ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

d.Display( “Hello” )d.Display( “Hello” )End SubEnd Sub

Page 90: Basic Concepts

Creating InterfacesCreating InterfacesPublic Interface personPublic Interface person

Sub SetName(ByVal PersonName As String)Sub SetName(ByVal PersonName As String)Function GetName( ) As StringFunction GetName( ) As String

End InterfaceEnd Interface

Public Class EmployeePublic Class EmployeeImplements personImplements personDim Name As StringDim Name As String

Sub SetName(ByVal PersonName As String) Implements Sub SetName(ByVal PersonName As String) Implements person.SetNameperson.SetName

Name = PersonNameName = PersonNameEnd SubEnd Sub

Function GetName( ) As String Implements Function GetName( ) As String Implements person.GetNameperson.GetName

Return NameReturn NameEnd FunctionEnd Function

End ClassEnd Class

Page 91: Basic Concepts

Multiple InterfacesMultiple InterfacesPublic Interface person ‘interface1Public Interface person ‘interface1

Sub SetName(ByVal PersonName As String)Sub SetName(ByVal PersonName As String)Function GetName( ) As StringFunction GetName( ) As String

End InterfaceEnd InterfacePublic Interface executive ‘interface2Public Interface executive ‘interface2

Sub SetTitle(ByVal PersonName As String)Sub SetTitle(ByVal PersonName As String)Function GetTitle( ) As StringFunction GetTitle( ) As StringSub SetName(ByVal ExecutiveTitle As String)Sub SetName(ByVal ExecutiveTitle As String)Function GetName( ) As StringFunction GetName( ) As String

End InterfaceEnd Interface

Public Class VicePresidentPublic Class VicePresidentImplements person, executiveImplements person, executiveDim Name As StringDim Name As StringDim Title As StringDim Title As String

Page 92: Basic Concepts

Continued…Continued…Sub SetTitle(ByVal ExecutiveTitle As String) Implements Sub SetTitle(ByVal ExecutiveTitle As String) Implements executive.SetTitleexecutive.SetTitle

Title = ExecutiveTitleTitle = ExecutiveTitleEnd SubEnd Sub

Function GetTitle( ) As String Implements executive.GetTitleFunction GetTitle( ) As String Implements executive.GetTitleReturn TitleReturn Title

End FunctionEnd Function

Sub SetName(ByVal PersonName As String) Implements Sub SetName(ByVal PersonName As String) Implements person.SetName, _person.SetName, _

executive.SetNameexecutive.SetNameName = PersonNameName = PersonName

End SubEnd Sub

Function GetName( ) As String Implements person.GetName. _Function GetName( ) As String Implements person.GetName. _executive.GetNameexecutive.GetNameReturn NameReturn Name

End FunctionEnd FunctionEnd ClassEnd Class

Page 93: Basic Concepts

Continued…Continued…

Public Class Form1Public Class Form1

Inherits System.Windows.Forms.FormInherits System.Windows.Forms.Form

Private Sub Button2_Click(ByVal) sender as System.Object,_Private Sub Button2_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

Dim Sam As New VicePresident( )Dim Sam As New VicePresident( )

Sam.SetName( “Sam” )Sam.SetName( “Sam” )

Sam.SetTitle( “vice president” )Sam.SetTitle( “vice president” )

TextBox1.Text = “You created ” & Sam.GetName( ) & TextBox1.Text = “You created ” & Sam.GetName( ) & “, ” & _“, ” & _

Sam.GetTitle( )Sam.GetTitle( )

End SubEnd Sub

End ClassEnd Class

Page 94: Basic Concepts

Interface Based Interface Based PolymorphismPolymorphism

Public Class Form1Public Class Form1

Inherits System.Windows.Forms.FormInherits System.Windows.Forms.Form

Private Sub Button2_Click(ByVal) sender as System.Object,_Private Sub Button2_Click(ByVal) sender as System.Object,_

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

Dim pet1 As New Animal2( )Dim pet1 As New Animal2( )

Dim pet2 As New Fish2( )Dim pet2 As New Fish2( )

Display2(pet1)Display2(pet1)

Display2(pet2)Display2(pet2)

End SubEnd Sub

Public Sub Display2(ByVal AnimalObject As Public Sub Display2(ByVal AnimalObject As AnimalInterface)AnimalInterface)

AnimalObject.Breathe( )AnimalObject.Breathe( )

End SubEnd Sub

Page 95: Basic Concepts

Continued…Continued…Public Interface AnimalInterfacePublic Interface AnimalInterface

Sub Breathe( )Sub Breathe( )End InterfaceEnd Interface

Public Class Animal2Public Class Animal2Implements AnimalInterfaceImplements AnimalInterfaceSub Breathe( ) Implements AnimalInterface.BreatheSub Breathe( ) Implements AnimalInterface.Breathe

MsgBox( “Breathing….” )MsgBox( “Breathing….” )End SubEnd Sub

End ClassEnd Class

Public Class Fish2Public Class Fish2Implements AnimalInterfaceImplements AnimalInterfaceSub Breathe( ) Implements AnimalInterface.BreatheSub Breathe( ) Implements AnimalInterface.Breathe

MsgBox( “Bubbling……” )MsgBox( “Bubbling……” )End SubEnd Sub

End ClassEnd Class

Page 96: Basic Concepts

Fields & Fields & PropertiesProperties

Page 97: Basic Concepts

OverviewOverview Fields, properties, methods and events are called the Fields, properties, methods and events are called the

members of a class. Inside the class, members are members of a class. Inside the class, members are declared as either Public, Private, Protected, Friend declared as either Public, Private, Protected, Friend or Protected Friend.or Protected Friend.

Public : Public : Gives variables public access, which means Gives variables public access, which means there are no restrictions on their accessibility.there are no restrictions on their accessibility.

Private : Private : Gives variables private access, which Gives variables private access, which means they are accessible only from within their means they are accessible only from within their class, including any nested procedure.class, including any nested procedure.

Protected : Protected : Gives variables protected access, which Gives variables protected access, which means they are accessible only from within their own means they are accessible only from within their own class or from a class derived from that class.class or from a class derived from that class.

Friend : Friend : Gives variables friend access. They are Gives variables friend access. They are accessible from within the program that contains accessible from within the program that contains their declaration and from anywhere else in the same their declaration and from anywhere else in the same assembly.assembly.

Page 98: Basic Concepts

FieldsFields

A member that represents a variable A member that represents a variable associated with an object or class.associated with an object or class.

To add a field to a classTo add a field to a class Declare a public variable in the class Declare a public variable in the class

definition, as in the following code: definition, as in the following code:

Class ThisClassClass ThisClass

Public ThisField As StringPublic ThisField As String

End ClassEnd Class

Page 99: Basic Concepts

PropertiesProperties You can use both properties and fields to store information in an You can use both properties and fields to store information in an

object. Whereas fields are simply public variables, properties object. Whereas fields are simply public variables, properties use property procedures to control how values are set or use property procedures to control how values are set or returned. Property procedures are blocks of code declared returned. Property procedures are blocks of code declared within property definitions that you can use to execute code within property definitions that you can use to execute code when a property value is set or retrieved. when a property value is set or retrieved.

Visual Basic has two types of property procedures: the Visual Basic has two types of property procedures: the GetGet property procedures for retrieving a property value, and the property procedures for retrieving a property value, and the SetSet property procedures for assigning a value to a property. For property procedures for assigning a value to a property. For example, a property that stores the balance of a bank account example, a property that stores the balance of a bank account might use code in a might use code in a GetGet property procedure to post interest and property procedure to post interest and check for service fees before returning the available balance. check for service fees before returning the available balance. You could then use the You could then use the SetSet property procedure to validate the property procedure to validate the balance and prevent it from being incorrectly updated. In short, balance and prevent it from being incorrectly updated. In short, property procedures allow an object to protect and validate its property procedures allow an object to protect and validate its own data.own data.

Page 100: Basic Concepts

Types of PropertiesTypes of Properties

There are following types of There are following types of properties:properties:

Read only propertiesRead only properties Write only propertiesWrite only properties ReadWrite propertiesReadWrite properties

Page 101: Basic Concepts

Creating Properties Creating Properties (ReadOnly)(ReadOnly)

Module Module1Module Module1Private PropertyValue As StringPrivate PropertyValue As StringPublic ReadOnly Property Prop1( ) Public ReadOnly Property Prop1( ) As StringAs String

GetGetReturn PropertyValueReturn PropertyValue

End GetEnd GetEnd PropertyEnd Property

End ModuleEnd Module

Page 102: Basic Concepts

Creating Properties Creating Properties (WriteOnly)(WriteOnly)

Module Module2Module Module2

Private PropertyValue As StringPrivate PropertyValue As String

Public WriteOnly Property Prop1( ) As Public WriteOnly Property Prop1( ) As StringString

Set(ByVal Value As String)Set(ByVal Value As String)

PropertyValue = ValuePropertyValue = Value

End SetEnd Set

End PropertyEnd Property

End ModuleEnd Module

Page 103: Basic Concepts

Methods, Events Methods, Events & Delegates& Delegates

Page 104: Basic Concepts

Methods OverviewMethods Overview

The methods of a class are just The methods of a class are just SubSub or or FunctionFunction procedures declared procedures declared within the class. within the class.

Page 105: Basic Concepts

Creating MethodsCreating Methods

Add a procedure declared as Add a procedure declared as PublicPublic, , as in the following code: as in the following code:

' Create a custom method on a form.' Create a custom method on a form.

Public Sub PrintMyJob()Public Sub PrintMyJob()

' Insert the code for your ' Insert the code for your method here.method here.

End SubEnd Sub

Page 106: Basic Concepts

EventsEvents

An event is a signal that informs an An event is a signal that informs an application that something application that something important has occurred. For important has occurred. For example, when a user clicks a example, when a user clicks a control on a form, the form can raise control on a form, the form can raise a a ClickClick event and call a procedure event and call a procedure that handles the event. that handles the event.

Page 107: Basic Concepts

Creating EventsCreating Events Declaration : Declaration :

[<attributelist>] [accessmodifier] [Shadows] [<attributelist>] [accessmodifier] [Shadows] Event event-name [(arglist)] [Implements interface interface-name]Event event-name [(arglist)] [Implements interface interface-name]

Example :Example :Public Class ClockTrackPublic Class ClockTrack

Public Event ThreeClick(ByVal Msg As String)Public Event ThreeClick(ByVal Msg As String)Public Sub Click( )Public Sub Click( )

Static ClickCount As Integer = 0Static ClickCount As Integer = 0ClickCount += 1ClickCount += 1If ClickCount >= 3 ThenIf ClickCount >= 3 Then

ClickCount = 0ClickCount = 0RaiseEvent ThreeClick( “You clicked three RaiseEvent ThreeClick( “You clicked three

times” )times” )End IfEnd If

End SubEnd SubEnd ClassEnd Class

Page 108: Basic Concepts

Continued…Continued…

Dim WithEvents traccker As New ClickTrack( )Dim WithEvents traccker As New ClickTrack( )

Public Sub tracker_ThreeClick(ByVal Msg As String) Handles Public Sub tracker_ThreeClick(ByVal Msg As String) Handles __

tracker.ThreeClicktracker.ThreeClick

TextBox1.Text = MsgTextBox1.Text = Msg

End SubEnd Sub

Private Sub Button1_Click(ByVal sender As System.Object, _Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.ClickByVal e As System.EventArgs) Handles Button1.Click

tracker.Click( )tracker.Click( )

End SubEnd Sub

Page 109: Basic Concepts

DelegatesDelegates The runtime supports reference types called The runtime supports reference types called

delegates that serve a purpose similar to that of delegates that serve a purpose similar to that of function pointers in C++.function pointers in C++.

Unlike function pointers, delegates are secure, Unlike function pointers, delegates are secure, verifiable, and type safe.verifiable, and type safe.

A delegate type can represent any method with a A delegate type can represent any method with a compatible signature.compatible signature.

While function pointers can only represent static While function pointers can only represent static functions, a delegate can represent both static and functions, a delegate can represent both static and instance methods.instance methods.

Delegates are used for event handlers and callback Delegates are used for event handlers and callback functions in the .NET Framework.functions in the .NET Framework.

Page 110: Basic Concepts

Creating DelegatesCreating DelegatesModule module1Module module1

Delegate Sub SubDelegate1(ByVal strText As String)Delegate Sub SubDelegate1(ByVal strText As String)

Sub Main( )Sub Main( )Dim Messager As SubDelegate1Dim Messager As SubDelegate1Messager = AddressOf DisplayMessageMessager = AddressOf DisplayMessageMessager.Invoke( “Hello” )Messager.Invoke( “Hello” )

End SubEnd Sub

Sub DisplayMessage(ByVal strText As String)Sub DisplayMessage(ByVal strText As String)System.Console.WriteLine( strText )System.Console.WriteLine( strText )

End SubEnd SubEnd ModuleEnd Module

Page 111: Basic Concepts

Constructor and Constructor and DestructorDestructor

Constructors are blocks of code that Constructors are blocks of code that run when a class is instantiatedrun when a class is instantiated

Destructors are blocks of code that Destructors are blocks of code that run when a class drops out of run when a class drops out of memorymemory

Constructors can be overloaded to Constructors can be overloaded to make them more powerfulmake them more powerful

Due to garbage collection, you Due to garbage collection, you cannot be assured of when cannot be assured of when destructors will executedestructors will execute

Page 112: Basic Concepts

Creating ConstructorsCreating Constructors To create a constructor, add a Sub procedure To create a constructor, add a Sub procedure

named named New New to a class.to a class. Example :Example :

Public Class DataClassPublic Class DataClassPrivate value As IntegerPrivate value As IntegerPublic Sub New(ByVal newVal As Integer)Public Sub New(ByVal newVal As Integer)

value = newValvalue = newValEnd SubEnd SubPublic Function GetData( ) As IntegerPublic Function GetData( ) As Integer

Return valueReturn valueEnd FunctionEnd Function

End ClassEnd Class

Page 113: Basic Concepts

Finalize and DisposeFinalize and Dispose

Finalize will run when the object Finalize will run when the object is cleaned up by the GCis cleaned up by the GC

You might want to release You might want to release resources explicitly, since you resources explicitly, since you cannot determine when Finalize cannot determine when Finalize will be calledwill be called

Use the Dispose design pattern Use the Dispose design pattern to explicitly free resourcesto explicitly free resources

Page 114: Basic Concepts

Creating DestructorCreating Destructor Finalize Finalize method is used for this purpose.method is used for this purpose. Example :Example :

Public Class Form1Public Class Form1Inherits System.Windows.Forms.FormInherits System.Windows.Forms.FormDim Object1 As New Class1( )Dim Object1 As New Class1( )

End ClassEnd Class

Public Class Class1Public Class Class1Protected Overrides Sub Finalize( )Protected Overrides Sub Finalize( )

Beep( )Beep( )End SubEnd Sub

End ClassEnd Class

Page 115: Basic Concepts

OverridingOverriding A derived class inherits the properties and A derived class inherits the properties and

methods defined in its base class. This is methods defined in its base class. This is useful because you can reuse these items useful because you can reuse these items when appropriate for the derived class.when appropriate for the derived class.

If the property or method in the base If the property or method in the base class is marked with the class is marked with the OverridableOverridable keyword, you can define a new keyword, you can define a new implementation for the member in the implementation for the member in the derived class.derived class.

Use the Use the OverridesOverrides keyword to shadow keyword to shadow the member by redefining it in the derived the member by redefining it in the derived class. This is useful when you cannot use class. This is useful when you cannot use the member "as is."the member "as is."

Page 116: Basic Concepts

Events Overriding ExampleEvents Overriding ExampleConst BonusRate As Decimal = 1.45DConst BonusRate As Decimal = 1.45DConst PayRate As Decimal = 14.75DConst PayRate As Decimal = 14.75D

Class PayrollClass Payroll Overridable Function PayEmployee( _Overridable Function PayEmployee( _ ByVal HoursWorked As Decimal, _ByVal HoursWorked As Decimal, _ ByVal PayRate As Decimal) _ByVal PayRate As Decimal) _ As DecimalAs Decimal

PayEmployee = HoursWorked * PayRatePayEmployee = HoursWorked * PayRate End FunctionEnd FunctionEnd ClassEnd Class

Class BonusPayrollClass BonusPayroll Inherits PayrollInherits Payroll Overrides Function PayEmployee( _Overrides Function PayEmployee( _ ByVal HoursWorked As Decimal, _ByVal HoursWorked As Decimal, _ ByVal PayRate As Decimal) _ByVal PayRate As Decimal) _ As DecimalAs Decimal

Page 117: Basic Concepts

Continued…Continued…' The following code calls the original method in the base ' The following code calls the original method in the base ' class, and then modifies the returned value.' class, and then modifies the returned value. PayEmployee = MyBase.PayEmployee(HoursWorked, PayEmployee = MyBase.PayEmployee(HoursWorked,

PayRate) * BonusRatePayRate) * BonusRate End FunctionEnd FunctionEnd ClassEnd Class

Sub RunPayroll()Sub RunPayroll() Dim PayrollItem As Payroll = New PayrollDim PayrollItem As Payroll = New Payroll Dim BonusPayrollItem As New BonusPayrollDim BonusPayrollItem As New BonusPayroll Dim HoursWorked As Decimal = 40Dim HoursWorked As Decimal = 40

MsgBox("Normal pay is: " & _MsgBox("Normal pay is: " & _ PayrollItem.PayEmployee(HoursWorked, PayRate))PayrollItem.PayEmployee(HoursWorked, PayRate)) MsgBox("Pay with bonus is: " & _MsgBox("Pay with bonus is: " & _ BonusPayrollItem.PayEmployee(HoursWorked, PayRate))BonusPayrollItem.PayEmployee(HoursWorked, PayRate))End SubEnd Sub

Page 118: Basic Concepts

OverloadingOverloading OverloadingOverloading a procedure means defining it in multiple a procedure means defining it in multiple

versions, using the same name but different parameter versions, using the same name but different parameter lists. The purpose of overloading is to define several closely lists. The purpose of overloading is to define several closely related versions of a procedure without having to related versions of a procedure without having to differentiate them by name. You do this by varying the differentiate them by name. You do this by varying the parameter list. parameter list.

Example:Example:Overloads Sub post(ByVal custName As String, ByVal Overloads Sub post(ByVal custName As String, ByVal amount As Single)amount As Single)

' Insert code to access customer record by customer name.' Insert code to access customer record by customer name.End SubEnd SubOverloads Sub post(ByVal custAcct As Integer, ByVal Overloads Sub post(ByVal custAcct As Integer, ByVal amount As Single)amount As Single)

' Insert code to access customer record by account number.' Insert code to access customer record by account number.End SubEnd Sub

Page 119: Basic Concepts

ShadowingShadowing

When two programming elements When two programming elements share the same name, one of them share the same name, one of them can hide, or can hide, or shadowshadow, the other one. , the other one. In such a situation, the shadowed In such a situation, the shadowed element is not available for element is not available for reference; instead, when your code reference; instead, when your code uses the element name, the Visual uses the element name, the Visual Basic compiler resolves it to the Basic compiler resolves it to the shadowing element.shadowing element.

Page 120: Basic Concepts

Shadowing ExampleShadowing Example

Module m

Procedure p

Public temp As Integer = 42

Dim temp As Integer = 5

Dim y As Integer = tempDim z As Integer = MyClass.temp

Local tempshadows member

Temp withinprocedure p

Page 121: Basic Concepts

ADO.NetADO.Net

Page 122: Basic Concepts

ADO.Net OverviewADO.Net Overview ADO.NET is a set of classes that expose ADO.NET is a set of classes that expose

data access services to the .NET data access services to the .NET programmer. ADO.NET provides a rich set programmer. ADO.NET provides a rich set of components for creating distributed, of components for creating distributed, data-sharing applications. It is an integral data-sharing applications. It is an integral part of the .NET Framework, providing part of the .NET Framework, providing access to relational, XML, and application access to relational, XML, and application data. ADO.NET supports a variety of data. ADO.NET supports a variety of development needs, including the creation development needs, including the creation of front-end database clients and middle-of front-end database clients and middle-tier business objects used by applications, tier business objects used by applications, tools, languages, or Internet browsers.tools, languages, or Internet browsers.

Page 123: Basic Concepts

Architecture of ADO.NetArchitecture of ADO.Net

.NET Framework Data Provider

Transaction

Connection

Parameters

Command

DataReader

DataAdapter

SelectCommand

InsertCommand

UpdateCommand

DeleteCommand

DataSet

DateTableCollection

DataRowCollection

DataColumnCollection

ConstraintCollection

DataRelationCollection

DataTable

XMLDatabase

Page 124: Basic Concepts

DataSetDataSet The ADO.NET DataSet is explicitly designed The ADO.NET DataSet is explicitly designed

for data access independent of any data for data access independent of any data source.source.

As a result, it can be used with multiple and As a result, it can be used with multiple and differing data sources, used with XML data, or differing data sources, used with XML data, or used to manage data local to the application.used to manage data local to the application.

The The DataSetDataSet contains a collection of one or contains a collection of one or more DataTable objects made up of rows and more DataTable objects made up of rows and columns of data, as well as primary key, columns of data, as well as primary key, foreign key, constraint, and relation foreign key, constraint, and relation information about the data in the information about the data in the DataTableDataTable objects. objects.

Page 125: Basic Concepts

Data ProviderData Provider

The System.Data.Common namespace The System.Data.Common namespace provides generic classes for working provides generic classes for working with data that let you write code that with data that let you write code that can work across different data can work across different data providers, as long as the data is providers, as long as the data is isomorphic. However, this does not take isomorphic. However, this does not take into account differences between into account differences between providers and database servers, which providers and database servers, which need to be handled by the developer on need to be handled by the developer on a case-by-case basis. a case-by-case basis.

Page 126: Basic Concepts

DataTableDataTable In ADO.NET, DataTable objects are used In ADO.NET, DataTable objects are used

to represent the tables in a to represent the tables in a DataSetDataSet. A . A DataTableDataTable represents one table of in- represents one table of in-memory relational data; the data is local memory relational data; the data is local to the .NET-based application in which it to the .NET-based application in which it resides, but can be populated from a data resides, but can be populated from a data source such as Microsoft SQL Server source such as Microsoft SQL Server using a using a DataAdapterDataAdapter

The following example creates an instance The following example creates an instance of a of a DataTableDataTable object and assigns it the object and assigns it the name "Customers.“name "Customers.“Dim workTable as DataTable = New Dim workTable as DataTable = New DataTable("Customers")DataTable("Customers")

Page 127: Basic Concepts

Continued…Continued…

The following example creates an The following example creates an instance of a instance of a DataTableDataTable by adding it to by adding it to the the TablesTables collection of a collection of a DataSetDataSet..

Dim customers As DataSet = New Dim customers As DataSet = New DataSetDataSet

Dim customersTable As DataTable = _Dim customersTable As DataTable = _

customers.Tables.Add("CustomersTable")customers.Tables.Add("CustomersTable")

Page 128: Basic Concepts

Accessing Data Through ADO.Net

Imports system.data.sqlclient //Top of the module.

Dim con as sqlconnection=new sqlconnection(“ConnectionString”)Con.open()Dim da as sqldataadapter =new sqldataadapter(“select * from

Student”,con)Dim com as sqlcommand=new sqlcommand(“select * from studetn

where rollno=@r”,con)Com.parameters.adwithvalue(“@r”,textbox1.text)Da.selectcommand=comDim ds as new dataset //we can use datatable also.Da.fill(ds)Datagridview1.datasource=dsDatagridvew1.refreshCon.close()

Page 129: Basic Concepts

GraphicsGraphics

Page 130: Basic Concepts

Graphics OverviewGraphics Overview GDI+ is an application programming interface (API) GDI+ is an application programming interface (API)

that forms the subsystem of the Microsoft Windows XP that forms the subsystem of the Microsoft Windows XP operating system. GDI+ is responsible for displaying operating system. GDI+ is responsible for displaying information on screens and printers. As its name information on screens and printers. As its name suggests, GDI+ is the successor to GDI, the Graphics suggests, GDI+ is the successor to GDI, the Graphics Device Interface included with earlier versions of Device Interface included with earlier versions of Windows. Windows.

The GDI+ API is exposed through a set of classes The GDI+ API is exposed through a set of classes deployed as managed code. This set of classes is called deployed as managed code. This set of classes is called the the managed class interfacemanaged class interface to GDI+. The following to GDI+. The following namespaces make up the managed class interface:namespaces make up the managed class interface:

System.DrawingSystem.Drawing System.Drawing.Drawing2DSystem.Drawing.Drawing2D System.Drawing.ImagingSystem.Drawing.Imaging System.Drawing.TextSystem.Drawing.Text System.Drawing.PrintingSystem.Drawing.Printing

Page 131: Basic Concepts

Drawing ObjectsDrawing Objects Before you can draw lines and shapes, Before you can draw lines and shapes,

render text, or display and manipulate render text, or display and manipulate images with GDI+, you need to create a images with GDI+, you need to create a Graphics object.Graphics object.

The The GraphicsGraphics object represents a GDI+ object represents a GDI+ drawing surface, and is the object that is drawing surface, and is the object that is used to create graphical images. used to create graphical images.

There are two steps in working with There are two steps in working with graphics: graphics:

Creating a Creating a GraphicsGraphics object. object. Using the Using the GraphicsGraphics object to draw lines object to draw lines

and shapes, render text, or display and and shapes, render text, or display and manipulate images.manipulate images.

Page 132: Basic Concepts

ExampleExample The following example shows how to reference a The following example shows how to reference a

GraphicsGraphics object from the object from the PaintEventArgsPaintEventArgs in in the the PaintPaint event: event:

Private Sub Form1_Paint(sender As Object, pe As Private Sub Form1_Paint(sender As Object, pe As PaintEventArgs) Handles _PaintEventArgs) Handles _

MyBase.PaintMyBase.Paint ' Declares the Graphics object and sets it to the ' Declares the Graphics object and sets it to the

Graphics objectGraphics object ' supplied in the PaintEventArgs.' supplied in the PaintEventArgs. Dim g As Graphics = pe.GraphicsDim g As Graphics = pe.Graphics ' Insert code to paint the form here.' Insert code to paint the form here.End SubEnd Sub

Page 133: Basic Concepts

Creating PensCreating Pens

The Pen Class defines an object used The Pen Class defines an object used to draw lines and curves. This class to draw lines and curves. This class cannot be inherited. cannot be inherited.

This example creates a Pen object.This example creates a Pen object.

Dim myPen As System.Drawing.PenDim myPen As System.Drawing.Pen

myPen = New myPen = New System.Drawing.Pen(System.DrawinSystem.Drawing.Pen(System.Drawing.Color.Tomato)g.Color.Tomato)

Page 134: Basic Concepts

Creating BrushesCreating Brushes

The Brush Class Defines objects The Brush Class Defines objects used to fill the interiors of graphical used to fill the interiors of graphical shapes such as rectangles, ellipses, shapes such as rectangles, ellipses, pies, polygons, and paths. pies, polygons, and paths.

GDI+ defines several fill styles: solid GDI+ defines several fill styles: solid color, hatch pattern, image texture, color, hatch pattern, image texture, and color gradient. and color gradient.

Page 135: Basic Concepts

Continued…Continued… This example creates a SolidBrush object that This example creates a SolidBrush object that

can be used by a Graphics object for filling can be used by a Graphics object for filling shapes.shapes.

Dim myBrush As New Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.ColSystem.Drawing.SolidBrush(System.Drawing.Color.Red)or.Red)

Dim formGraphics As System.Drawing.GraphicsDim formGraphics As System.Drawing.GraphicsformGraphics = Me.CreateGraphics()formGraphics = Me.CreateGraphics()formGraphics.FillEllipse(myBrush, New formGraphics.FillEllipse(myBrush, New

Rectangle(0, 0, 200, 300))Rectangle(0, 0, 200, 300))myBrush.Dispose()myBrush.Dispose()formGraphics.Dispose()formGraphics.Dispose()

Page 136: Basic Concepts

Filling ObjectsFilling Objects This example draws a filled rectangle on a This example draws a filled rectangle on a

form.form.Dim myBrush As New Dim myBrush As New

System.Drawing.SolidBrush(System.Drawing.System.Drawing.SolidBrush(System.Drawing.Color.Red)Color.Red)

Dim formGraphics As System.Drawing.GraphicsDim formGraphics As System.Drawing.GraphicsformGraphics = Me.CreateGraphics()formGraphics = Me.CreateGraphics()formGraphics.FillRectangle(myBrush, New formGraphics.FillRectangle(myBrush, New

Rectangle(0, 0, 200, 300))Rectangle(0, 0, 200, 300))myBrush.Dispose()myBrush.Dispose()formGraphics.Dispose()formGraphics.Dispose()

Page 137: Basic Concepts

Continued…Continued… This example draws a filled ellipse on a form.This example draws a filled ellipse on a form.Dim myBrush As New Dim myBrush As New

System.Drawing.SolidBrush(System.DrawingSystem.Drawing.SolidBrush(System.Drawing.Color.Red).Color.Red)

Dim formGraphics As Dim formGraphics As System.Drawing.GraphicsSystem.Drawing.Graphics

formGraphics = Me.CreateGraphics()formGraphics = Me.CreateGraphics()formGraphics.FillEllipse(myBrush, New formGraphics.FillEllipse(myBrush, New

Rectangle(0, 0, 200, 300))Rectangle(0, 0, 200, 300))myBrush.Dispose()myBrush.Dispose()formGraphics.Dispose()formGraphics.Dispose()

Page 138: Basic Concepts

Releasing ObjectsReleasing Objects

Dispose method releases all Dispose method releases all resources used by a particular resources used by a particular object.object.

Example: Releases all resources Example: Releases all resources used by this Penused by this Pen

Dim Dim instanceinstance As Pen As Pen

instanceinstance.Dispose .Dispose

Page 139: Basic Concepts

Crystal ReportCrystal Report

Page 140: Basic Concepts

Crystal ReportCrystal Report Crystal Reports has been part of Visual Studio since 1993, and Crystal Reports has been part of Visual Studio since 1993, and

is now the standard for reporting in Visual Studio 2005. It is now the standard for reporting in Visual Studio 2005. It ships with every copy of Visual Studio 2005 and is integrated ships with every copy of Visual Studio 2005 and is integrated directly into the development environment.directly into the development environment.

Crystal Reports for Visual Studio 2005 brings the ability to Crystal Reports for Visual Studio 2005 brings the ability to create interactive, presentation-quality content to the Windows create interactive, presentation-quality content to the Windows environment. With Crystal Reports for Visual Studio 2005, you environment. With Crystal Reports for Visual Studio 2005, you can create complex and professional reports in a GUI-based can create complex and professional reports in a GUI-based program. Then you can connect your report to almost any program. Then you can connect your report to almost any database source, as well as to proxy data, such as a result set database source, as well as to proxy data, such as a result set (for example, an ADO.NET DataSet). With the wizards included (for example, an ADO.NET DataSet). With the wizards included in the GUI designer, you can easily set formatting, grouping, in the GUI designer, you can easily set formatting, grouping, charting, and other criteria.charting, and other criteria.

You can host your report in either a Web or Windows You can host your report in either a Web or Windows application, with one of the Crystal Reports for Visual Studio application, with one of the Crystal Reports for Visual Studio 2005 viewer controls. Report presentation in both Windows 2005 viewer controls. Report presentation in both Windows and HTML 3.2 or 4.0 clients is highly interactive and provides and HTML 3.2 or 4.0 clients is highly interactive and provides you with features such as chart drill down, report navigation, you with features such as chart drill down, report navigation, and text search.and text search.