0% found this document useful (0 votes)
6 views42 pages

VB NET Complete Study Notes

This document is a comprehensive study guide for VB.NET programming, covering fundamental concepts such as program structure, data types, control structures, and object-oriented programming principles. It includes detailed sections on arrays, string handling, and database connectivity with ADO.NET, along with examples and explanations of operators, expressions, and debugging techniques. The guide serves as a resource for both beginners and experienced programmers looking to enhance their knowledge of VB.NET.

Uploaded by

cutegamer7200
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views42 pages

VB NET Complete Study Notes

This document is a comprehensive study guide for VB.NET programming, covering fundamental concepts such as program structure, data types, control structures, and object-oriented programming principles. It includes detailed sections on arrays, string handling, and database connectivity with ADO.NET, along with examples and explanations of operators, expressions, and debugging techniques. The guide serves as a resource for both beginners and experienced programmers looking to enhance their knowledge of VB.NET.

Uploaded by

cutegamer7200
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

VB.

NET
Complete Programming Study Notes

Fundamentals to Object-Oriented Programming


[Link] Programming - Complete Study Notes

Table of Contents
(Right-click and select "Update Field" to refresh page numbers)

1. Introduction to [Link].....................................................................................................................3

2. Program Structure............................................................................................................................4

3. Data Types, Variables and Constants.................................................................................................5

4. Operators and Expressions...............................................................................................................7

5. Control Structures............................................................................................................................9

6. Arrays.............................................................................................................................................13

7. String Handling...............................................................................................................................15

8. Sub Procedures and Functions........................................................................................................17

9. Windows Forms and Controls.........................................................................................................20

10. Menus and Dialog Boxes...............................................................................................................23

11. Object-Oriented Programming Fundamentals...............................................................................26

12. Classes and Objects......................................................................................................................29

13. Inheritance and Polymorphism.....................................................................................................33

14. Database Connectivity with [Link]...........................................................................................36

15. Debugging Techniques..................................................................................................................39

Page 2
[Link] Programming - Complete Study Notes

1. Introduction to [Link]
[Link] (Visual Basic .NET) is a modern, object-oriented programming language developed by
Microsoft as part of the .NET framework.

1.1 Key Features of [Link]


• Object-Oriented:Fully supports OOP principles including encapsulation, inheritance, and
polymorphism.

• Platform Independent:Applications run on the Common Language Runtime (CLR), making


them portable.

• Rich Library:The .NET Framework provides extensive libraries for file I/O, networking,
database access, and GUI development.

• Automatic Memory Management:The garbage collector automatically handles memory


allocation and deallocation.

1.2 The .NET Framework


The .NET Framework is a software development platform that provides:

0. Common Language Runtime (CLR):The execution engine that manages running applications.

1. Framework Class Library (FCL):A comprehensive collection of reusable classes, interfaces,


and value types.

2. Development Tools:Visual Studio IDE for building, debugging, and deploying applications.

1.3 Visual Studio IDE


Visual Studio is the primary Integrated Development Environment (IDE) for [Link] development. Key
components include:

• Solution Explorer:Displays project files and structure.

• Properties Window:View and modify control properties.

• Toolbox:Contains controls to drag onto forms.

• Code Editor:Write and edit code with IntelliSense.

• Form Designer:Visual design surface for Windows Forms.

Page 3
[Link] Programming - Complete Study Notes

2. Program Structure
Every [Link] program follows a standard structure with imports, modules or classes, and the
Main method as the entry point.

2.1 Basic Program Structure


A simple [Link] console program consists of the following components:
Imports System

Module Program
Sub Main()
' This is the entry point of the program
[Link]("Hello, World!")
[Link]() ' Keeps console window open
End Sub
End Module

2.2 Components Explained


Declares namespaces needed for the program. System is commonly used for
Imports
basic I/O operations.

Module A container for code. In [Link], code must be placed inside a Module or Class.

The entry point where program execution begins. Every application must have
Sub Main()
one Main method.

[Link]() A method to output text to the console window.

' Comment Single-line comments start with an apostrophe.

REM Comment Alternative comment syntax using REM keyword.

2.3 Windows Forms Application Structure


Public Class Form1
Inherits [Link]

' Form Load event


Private Sub Form1_Load(sender As Object, e As EventArgs) _n
Handles [Link]
' Initialization code
End Sub
End Class

Page 4
[Link] Programming - Complete Study Notes

3. Data Types, Variables and Constants

3.1 Common Data Types


[Link] supports various data types for storing different kinds of data:

Data Type Example Description

Integer 25 Whole numbers (-2,147,483,648 to 2,147,483,647)

Long 1000000 Large whole numbers

Double 99.99 Floating-point numbers with decimal places

Decimal 123.456D High-precision decimal for financial calculations

String Hello Text data enclosed in double quotes

Boolean True/False Logical values

Date 01/01/2024 Date and time values

Char A Single character

Object Any type Can hold any type of data

3.2 Variable Declaration


Variables are declared using the Dim keyword followed by the variable name and data type:
' Explicit declaration with type
Dim age As Integer = 25
Dim price As Double = 99.99
Dim name As String = "John"
Dim isAvailable As Boolean = True

' Multiple variables of same type


Dim x, y, z As Integer ' All are Integer
Dim firstName, lastName As String

' Implicit typing (Option Infer On)


Dim value = 100 ' Compiler infers Integer

3.3 Variable Naming Rules


• Must begin:with a letter or underscore.

• Can contain:letters, digits, and underscores only.

• Cannot be:a reserved keyword (e.g., If, Then, Sub).

• Case-insensitive:in [Link] (Age and age are the same).

• Use meaningful names:like customerName instead of cn.

Page 5
[Link] Programming - Complete Study Notes

3.4 Constants
Constants are values that cannot be changed during program execution. They are declared using the
Const keyword:
Const Pi As Double = 3.14159
Const MaxScore As Integer = 100
Const AppName As String = "MyApplication"
Const TaxRate As Decimal = 0.08D

' Using constants


Dim circleArea As Double = Pi * radius ^ 2

Constants improve code readability and maintainability. Use them for values that should never
change, such as mathematical constants, tax rates, or application settings.

3.5 Scope and Lifetime


Local Variable Declared inside a procedure. Only accessible within that procedure.

Module-Level Variable Declared at module level with Private. Accessible throughout the module.

Global Variable Declared with Public at module level. Accessible throughout the application.

Static Variable Declared with Static keyword. Retains value between procedure calls.

Page 6
[Link] Programming - Complete Study Notes

4. Operators and Expressions


Operators are symbols that perform operations on operands (variables or values). Expressions
combine operands and operators to produce results.

4.1 Arithmetic Operators


Operator Name Description

+ Addition Adds two values

- Subtraction Subtracts second value from first

* Multiplication Multiplies two values

/ Division Divides first value by second (returns Double)

\ Integer Division Divides and truncates decimal

Mod Modulus Returns remainder of division

^ Exponentiation Raises first value to power of second

4.2 Arithmetic Expression Examples


Dim num1 As Integer = 10
Dim num2 As Integer = 3

Dim sum As Integer = num1 + num2 ' 13


Dim difference As Integer = num1 - num2 ' 7
Dim product As Integer = num1 * num2 ' 30
Dim quotient As Double = num1 / num2 ' 3.333...
Dim remainder As Integer = num1 Mod num2 ' 1
Dim power As Double = num1 ^ num2 ' 1000 (10^3)

' Integer division (truncates decimal)


Dim intResult As Integer = num1 \\ num2 ' 3

4.3 Relational Operators


Relational operators compare two values and return a Boolean result (True or False):

Operator Name Example

= Equal To If x = 5 Then

<> Not Equal To If x <> 0 Then

> Greater Than If age > 18 Then

< Less Than If score < 60 Then

>= Greater Than or Equal If grade >= 70 Then

Page 7
[Link] Programming - Complete Study Notes

<= Less Than or Equal If count <= 100 Then

4.4 Relational Comparison Examples


Dim age As Integer = 25
Dim name As String = "John"

' Numeric comparisons


If age >= 18 Then
[Link]("Adult")
End If

' String comparisons (case-sensitive)


If name = "John" Then
[Link]("Name matches")
End If

' String comparison rules:


' - "JOAN" < "JOHN" (A comes before O)
' - "HOPE" < "HOPELESS" (shorter string is less)
' - Numbers < Letters ("300ZX" < "Porsche")

4.5 Logical Operators


Logical operators combine Boolean values and are commonly used in conditional statements:

Operator Name Description

And Logical AND True if both conditions are true

Or Logical OR True if at least one condition is true

Not Logical NOT Reverses the Boolean value

AndAlso Short-circuit AND And that stops if first is false (more efficient)

OrElse Short-circuit OR Or that stops if first is true (more efficient)

Xor Exclusive OR True if exactly one condition is true

4.6 Logical Expression Examples


Dim isAdult As Boolean = True
Dim hasID As Boolean = False

' AND - both must be true


If isAdult And hasID Then
[Link]("Entry allowed")
End If

' OR - at least one must be true


If isAdult Or hasID Then
[Link]("At least one condition met")
End If

' NOT - negation


If Not hasID Then
[Link]("ID is required")
End If

Page 8
[Link] Programming - Complete Study Notes

' Short-circuit operators (more efficient)


If isAdult AndAlso hasID Then ' Stops if isAdult is False
[Link]("Entry allowed")
End If

If isAdult OrElse hasID Then ' Stops if isAdult is True


[Link]("Condition met")
End If

4.7 Operator Precedence


Operators are evaluated in this order (highest to lowest):

3. Parentheses:() - Highest priority, use to override precedence

4. Exponentiation:^

5. Unary:+, -, Not

6. Multiplicative:*, /, \, Mod

7. Additive:+, -

8. Relational:=, <>, <, >, <=, >=

9. Logical:And, Or, AndAlso, OrElse

Page 9
[Link] Programming - Complete Study Notes

5. Control Structures
Control structures determine the flow of program execution based on conditions and loops.

5.1 If...Then...Else Statements


The If statement executes code based on a condition. Block If statements must always conclude with
End If.
' Simple If
If age >= 18 Then
[Link]("Adult")
End If

' If...Else
If temperature > 80 Then
[Link] = "Hot"
Else
[Link] = "Moderate"
End If

' If...ElseIf...Else
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
ElseIf score >= 60 Then
grade = "D"
Else
grade = "F"
End If

Tip:ElseIf is one word, but End If is two words. Then must be on the same line as If or ElseIf.

5.2 Nested If Statements


If tempInteger > 32 Then
If tempInteger > 80 Then
[Link] = "Hot"
Else
[Link] = "Moderate"
End If
Else
[Link] = "Freezing"
End If

5.3 Select Case Statement


Select Case provides a cleaner way to handle multiple conditions compared to multiple If statements:
Dim day As Integer = 3

Select Case day


Case 1
[Link]("Monday")
Case 2

Page 10
[Link] Programming - Complete Study Notes

[Link]("Tuesday")
Case 3
[Link]("Wednesday")
Case 4, 5
[Link]("Thursday or Friday")
Case 6 To 7
[Link]("Weekend")
Case Else
[Link]("Invalid day")
End Select

' Using relational operators with Is


Select Case age
Case Is < 13
category = "Child"
Case Is < 20
category = "Teenager"
Case Is < 65
category = "Adult"
Case Else
category = "Senior"
End Select

5.4 Loops

For...Next Loop
Used when you know the exact number of iterations:
' Count from 1 to 5
For i As Integer = 1 To 5
[Link]("Iteration: " & i)
Next

' Count with a step


For i As Integer = 10 To 0 Step -2
[Link](i) ' Outputs: 10, 8, 6, 4, 2, 0
Next

' Exit For example


For i As Integer = 1 To 100
If i = 50 Then
Exit For ' Exit loop early
End If
Next

Do...While Loop
Repeats while a condition is true. The condition is checked before each iteration:
Dim counter As Integer = 1

Do While counter <= 5


[Link]("Counter: " & counter)
counter += 1 ' Increment counter
Loop

Do...Until Loop
Repeats until a condition becomes true:
Dim counter As Integer = 1

Page 11
[Link] Programming - Complete Study Notes

Do Until counter > 5


[Link]("Counter: " & counter)
counter += 1
Loop

Do...Loop While/Until (Post-test)


The condition is checked after each iteration, so the loop executes at least once:
Dim response As String

Do
[Link]("Enter a value (or 'quit' to exit):")
response = [Link]()
Loop Until [Link]() = "QUIT"

For Each Loop


Iterates through each element in a collection or array:
Dim fruits As String() = {"Apple", "Banana", "Orange"}

For Each fruit In fruits


[Link](fruit)
Next

' For Each with List


Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
For Each num In numbers
sum += num
Next

Page 12
[Link] Programming - Complete Study Notes

6. Arrays
Arrays store multiple values of the same data type in a single variable.

6.1 Declaring and Initializing Arrays


' Method 1: Declare and initialize together
Dim fruits As String() = {"Apple", "Banana", "Orange"}

' Method 2: Declare with size, then assign values


Dim numbers(4) As Integer ' Array with 5 elements (0 to 4)
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
numbers(3) = 40
numbers(4) = 50

' Method 3: Using New keyword


Dim scores As Integer() = New Integer(2) {85, 90, 95}

' Method 4: Empty array declaration


Dim names() As String

6.2 Accessing Array Elements


Dim names As String() = {"Alice", "Bob", "Charlie"}

' Access individual elements (index starts at 0)


[Link](names(0)) ' Outputs: Alice
[Link](names(1)) ' Outputs: Bob

' Modify an element


names(1) = "Robert"

' Get array length


[Link]([Link]) ' Outputs: 3

' Get upper bound (last index)


[Link]([Link](0)) ' Outputs: 2

6.3 Array Methods


Dim numbers As Integer() = {5, 2, 8, 1, 9}

' Sort array


[Link](numbers) ' {1, 2, 5, 8, 9}

' Reverse array


[Link](numbers) ' {9, 8, 5, 2, 1}

' Search for element


Dim index As Integer = [Link](numbers, 5) ' Returns 2 or -1 if not
found

' Clear elements


[Link](numbers, 0, 2) ' Clear first 2 elements

' Copy array


Dim copy() As Integer = New Integer([Link] - 1) {}

Page 13
[Link] Programming - Complete Study Notes

[Link](numbers, copy, [Link])

6.4 Multidimensional Arrays


' 2D array (rectangular)
Dim matrix(2, 2) As Integer ' 3x3 matrix
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(1, 0) = 3
matrix(1, 1) = 4

' Initialize 2D array


Dim grid(,) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

' Get dimensions


[Link]([Link](0)) ' Rows: 3
[Link]([Link](1)) ' Columns: 3

' Iterate 2D array


For row As Integer = 0 To [Link](0) - 1
For col As Integer = 0 To [Link](1) - 1
[Link](grid(row, col) & " ")
Next
[Link]()
Next

6.5 Jagged Arrays


Jagged arrays are arrays of arrays where each sub-array can have different lengths:
' Declare jagged array
Dim jagged()() As Integer = New Integer(2)() {}

' Initialize sub-arrays


jagged(0) = New Integer() {1, 2}
jagged(1) = New Integer() {3, 4, 5}
jagged(2) = New Integer() {6, 7, 8, 9}

' Access elements


[Link](jagged(1)(2)) ' Outputs: 5

6.6 Dynamic Arrays with List(Of T)


' List is more flexible than array
Dim names As New List(Of String)

' Add items


[Link]("Alice")
[Link]("Bob")
[Link]("Charlie")

' Insert at position


[Link](1, "David")

' Remove item


[Link]("Bob")
[Link](0)

' Count items


[Link]([Link]) ' Outputs: 2

' Check if contains


If [Link]("Alice") Then

Page 14
[Link] Programming - Complete Study Notes

[Link]("Found")
End If

' Convert to array


Dim namesArray() As String = [Link]()

Page 15
[Link] Programming - Complete Study Notes

7. String Handling
Strings are sequences of characters. [Link] provides many methods for manipulating strings.

7.1 Common String Methods


Method Description

ToUpper() Converts string to uppercase

ToLower() Converts string to lowercase

Trim() Removes leading and trailing whitespace

Substring(start,
Extracts portion of string
length)

Length Returns number of characters

Replace(old, new) Replaces occurrences of substring

IndexOf(substring) Returns position of substring (or -1)

Contains(substring) Returns True if substring exists

Split(separator) Divides string into array

StartsWith(substring) Returns True if string starts with substring

EndsWith(substring) Returns True if string ends with substring

7.2 String Method Examples


Dim text As String = " Hello World "

' Trim whitespace


text = [Link]() ' "Hello World"

' Case conversion


Dim upper As String = [Link]() ' "HELLO WORLD"
Dim lower As String = [Link]() ' "hello world"

' Substring
Dim subStr As String = [Link](0, 5) ' "Hello"

' Length
Dim len As Integer = [Link] ' 11

' Replace
Dim newText As String = [Link]("World", "[Link]") ' "Hello [Link]"

' IndexOf
Dim pos As Integer = [Link]("World") ' 6 (or -1 if not found)

' Contains
Dim hasWord As Boolean = [Link]("Hello") ' True

Page 16
[Link] Programming - Complete Study Notes

' Split
Dim words() As String = [Link](" "c) ' {"Hello", "World"}

' Join
Dim joined As String = [Link](" - ", words) ' "Hello - World"

7.3 String Concatenation


Dim firstName As String = "John"
Dim lastName As String = "Doe"

' Using & operator (preferred in [Link])


Dim fullName As String = firstName & " " & lastName

' Using + operator


Dim name As String = firstName + " " + lastName

' Using [Link]


Dim result As String = [Link](firstName, " ", lastName)

' Using [Link]


Dim message As String = [Link]("Hello, {0} {1}", firstName, lastName)

' Using interpolated strings (VB 14+)


Dim greeting As String = $"Hello, {firstName} {lastName}"

7.4 ControlChars Constants


ControlChars provides constants for special characters:

Constant Description

[Link] Carriage Return

[Link] Carriage Return + Line Feed

[Link] New line (CrLf)

[Link] Tab character

[Link] Character with value of zero

[Link] Quotation mark character

' Using ControlChars for multi-line output


Dim message As String = "Total Sales: " & [Link]("C") & _n
[Link] & "Average Sale: " & [Link]("C")

[Link](message, "Sales Summary", [Link])

' Using [Link] for alignment


Dim report As String = "Name" & [Link] & "Score" &
[Link] & _n "Alice" & [Link] &
"95" & [Link] & _n "Bob" &
[Link] & "87"

Page 17
[Link] Programming - Complete Study Notes

8. Sub Procedures and Functions


Procedures are reusable blocks of code. Sub procedures perform actions, while Functions perform
actions and return a value.

8.1 Sub Procedures


A Sub procedure performs an action but does not return a value:
' Declaring a Sub procedure
Private Sub DisplayMessage(message As String)
[Link](message)
End Sub

' Calling a Sub procedure


DisplayMessage("Hello, World!")

' Sub with multiple parameters


Private Sub CalculateArea(length As Double, width As Double)
Dim area As Double = length * width
[Link]("Area: " & area)
End Sub

CalculateArea(10.5, 20.0)

8.2 Function Procedures


A Function performs an action and returns a value:
' Declaring a Function
Private Function AddNumbers(a As Integer, b As Integer) As Integer
Return a + b
End Function

' Using the return value


Dim sum As Integer = AddNumbers(5, 3)
[Link](sum) ' Outputs: 8

' Alternative return syntax (older style)


Private Function Multiply(x As Double, y As Double) As Double
Multiply = x * y ' Assign to function name
End Function

8.3 Passing Arguments ByVal and ByRef


Arguments can be passed by value (ByVal) or by reference (ByRef):

Passes a copy of the value. Changes to the parameter do not affect the original
ByVal (default)
variable.

Passes a reference to the memory location. Changes to the parameter affect the
ByRef
original variable.

' ByVal example (default)


Private Sub ModifyByVal(ByVal num As Integer)
num = 100 ' Only changes local copy

Page 18
[Link] Programming - Complete Study Notes

End Sub

Dim value As Integer = 50


ModifyByVal(value)
[Link](value) ' Still 50

' ByRef example


Private Sub ModifyByRef(ByRef num As Integer)
num = 100 ' Changes original variable
End Sub

Dim value2 As Integer = 50


ModifyByRef(value2)
[Link](value2) ' Now 100

8.4 Functions with Multiple Arguments


' Function with multiple parameters
Private Function CalculatePayment(_n ByVal rate As Decimal, _n ByVal
years As Decimal, _n ByVal principal As Decimal) As Decimal

' Simple interest calculation


Return principal * rate * years
End Function

' Calling with multiple arguments


Dim payment As Decimal = CalculatePayment(0.05D, 5D, 10000D)

8.5 Optional Parameters


' Function with optional parameter
Private Function Greet(name As String, _n Optional greeting As String =
"Hello") As String
Return greeting & ", " & name
End Function

' Call with optional parameter


[Link](Greet("John")) ' "Hello, John"
[Link](Greet("John", "Hi")) ' "Hi, John"

8.6 Overloading Procedures


Overloading allows multiple procedures with the same name but different parameter lists:
' Overloaded Sub procedures
Private Sub Display(value As Integer)
[Link]("Integer: " & value)
End Sub

Private Sub Display(value As String)


[Link]("String: " & value)
End Sub

Private Sub Display(value As Double)


[Link]("Double: " & value)
End Sub

' Compiler determines which to call


Display(100) ' Calls Integer version
Display("Test") ' Calls String version
Display(99.99) ' Calls Double version

Page 19
[Link] Programming - Complete Study Notes

9. Windows Forms and Controls


Windows Forms is a GUI framework for building desktop applications with visual controls like
buttons, text boxes, and labels.

9.1 Creating a Windows Forms Application


Steps to create a Windows Forms project in Visual Studio:

10. Create Project:Open Visual Studio and create a new Windows Forms App (.NET Framework)
project.

11. Design the Form:Drag and drop controls from the Toolbox onto the form.

12. Set Properties:Modify control properties (Name, Text, Size, etc.) in the Properties window.

13. Write Event Code:Double-click controls to create event handlers and write code.

9.2 Common Controls


Control Common Properties Purpose

Button Text, Name, Enabled Triggers an action when clicked

Text, Name, ReadOnly,


TextBox Accepts user text input
Multiline

Label Text, Name, Font, AutoSize Displays read-only text

Items, SelectedItem,
ComboBox Dropdown list of options
DropDownStyle

Items, SelectedIndex,
ListBox Displays list of items
SelectionMode

CheckBox Checked, Text Boolean option selector

RadioButton Checked, GroupName Single option selector from group

DataSource, Columns,
DataGridView Displays tabular data
ReadOnly

PictureBox Image, SizeMode Displays images

Panel BorderStyle, AutoScroll Container for grouping controls

9.3 Control Properties


' Common properties for most controls
[Link] = "btnSubmit" ' Identifier for the control
[Link] = "Submit" ' Display text

Page 20
[Link] Programming - Complete Study Notes

[Link] = True ' Can user interact?


[Link] = True ' Is control visible?
[Link] = [Link] ' Background color
[Link] = [Link] ' Text color
[Link] = New Font("Arial", 12)
[Link] = New Point(10, 20) ' Position on form
[Link] = New Size(100, 30) ' Width and height

9.4 Working with TextBox


' Get text from TextBox
Dim input As String = [Link]

' Set text in TextBox


[Link] = "Hello, " & input

' Clear TextBox


[Link]()
' or
[Link] = [Link]

' Check if empty


If [Link]([Link]) Then
[Link]("Please enter a name")
End If

' Convert to number


Dim age As Integer = [Link]([Link])
Dim price As Decimal = [Link]([Link])

9.5 Working with Radio Buttons and Check Boxes


' Radio Button - single selection from group
If [Link] Then
gender = "Male"
ElseIf [Link] Then
gender = "Female"
End If

' Check Box - multiple selections allowed


If [Link] Then
ApplyDiscount()
End If

' Set checked state


[Link] = True

9.6 Simple Button Click Example


Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) _n
Handles [Link]

' Get input from text boxes


Dim num1 As Double = [Link]([Link])
Dim num2 As Double = [Link]([Link])

' Perform calculation


Dim sum As Double = num1 + num2

' Display result


[Link] = [Link]()
End Sub

Page 21
[Link] Programming - Complete Study Notes

End Class

Page 22
[Link] Programming - Complete Study Notes

10. Menus and Dialog Boxes


Menus provide organized access to application features. Dialog boxes are pre-built windows for
common tasks like opening files or selecting colors.

10.1 Creating Menus


To create menus in Windows Forms:

14. Add MenuStrip:Drag MenuStrip control from Toolbox to form (appears in component tray).

15. Type Menu Items:Click "Type Here" on form and type menu text.

16. Set Access Keys:Use & symbol for keyboard access (e.g., &File for Alt+F).

17. Name Properties:Change Name property for each menu item (e.g., fileMenu,
exitMenuItem).
' Menu item click event handler
Private Sub exitMenuItem_Click(sender As Object, e As EventArgs) _n
Handles [Link]
[Link]()
End Sub

Private Sub aboutMenuItem_Click(sender As Object, e As EventArgs) _n


Handles [Link]
[Link]("Version 1.0", "About")
End Sub

10.2 Menu Properties


Enabled True/False - Determines if menu item can be selected.

Checked True/False - Shows checkmark next to item (for toggle options).

ShortcutKeys Keyboard shortcut (e.g., Ctrl+S for Save).

Visible True/False - Shows or hides the menu item.

10.3 Context Menus


Context menus (right-click menus) provide options specific to a control:
' Add ContextMenuStrip to form
' Set control's ContextMenuStrip property to the menu

Private Sub cutMenuItem_Click(sender As Object, e As EventArgs) _n


Handles [Link]
[Link]()
End Sub

Private Sub copyMenuItem_Click(sender As Object, e As EventArgs) _n


Handles [Link]
[Link]()

Page 23
[Link] Programming - Complete Study Notes

End Sub

Private Sub pasteMenuItem_Click(sender As Object, e As EventArgs) _n


Handles [Link]
[Link]()
End Sub

10.4 MessageBox
MessageBox displays information and captures user responses:
' Simple message
[Link]("Operation completed successfully")

' Message with title


[Link]("File saved", "Success")

' Message with buttons and icon


Dim result As DialogResult = [Link](_n "Do you want to save
changes?", _n "Confirm", _n [Link], _n
[Link])

If result = [Link] Then


SaveFile()
ElseIf result = [Link] Then
' Continue without saving
Else
' Cancel operation
End If

10.5 Common Dialog Boxes


Common Dialog controls provide standard Windows dialogs:

Dialog Purpose

OpenFileDialog Browse and select files to open

SaveFileDialog Specify filename and location for saving

FontDialog Select font family, size, and style

ColorDialog Select colors from palette

PrintDialog Configure print settings

PrintPreviewDialog Preview document before printing

FolderBrowserDialog Browse and select folders

10.6 OpenFileDialog Example


Private Sub openMenuItem_Click(sender As Object, e As EventArgs) _n
Handles [Link]

With OpenFileDialog1
.Title = "Open Text File"
.Filter = "Text Files|*.txt|All Files|*.*"
.InitialDirectory = "C:\\Documents"

Page 24
[Link] Programming - Complete Study Notes

If .ShowDialog() = [Link] Then


[Link] = [Link](.FileName)
End If
End With
End Sub

10.7 SaveFileDialog Example


Private Sub saveMenuItem_Click(sender As Object, e As EventArgs) _n
Handles [Link]

With SaveFileDialog1
.Title = "Save File"
.Filter = "Text Files|*.txt|All Files|*.*"
.FileName = "[Link]"

If .ShowDialog() = [Link] Then


[Link](.FileName, [Link])
[Link]("File saved successfully!")
End If
End With
End Sub

10.8 FontDialog and ColorDialog


' FontDialog
Private Sub fontMenuItem_Click(sender As Object, e As EventArgs) _n
Handles [Link]

[Link] = [Link] ' Set initial font

If [Link]() = [Link] Then


[Link] = [Link]
End If
End Sub

' ColorDialog
Private Sub colorMenuItem_Click(sender As Object, e As EventArgs) _n
Handles [Link]

[Link] = [Link] ' Set initial color

If [Link]() = [Link] Then


[Link] = [Link]
End If
End Sub

Page 25
[Link] Programming - Complete Study Notes

11. Object-Oriented Programming Fundamentals


Object-Oriented Programming (OOP) is a programming paradigm based on objects that contain
data and methods. [Link] fully supports OOP principles.

11.1 Key OOP Concepts


Object An instance of a class. Objects have state (data) and behavior (methods).

A blueprint or template for creating objects. Defines what data and methods
Class
objects will have.

Encapsulation Bundling data and methods together, hiding internal details from the outside.

Inheritance Creating new classes from existing ones, reusing and extending functionality.

Polymorphism Ability to use the same method name for different implementations.

Abstraction Hiding complex implementation details and showing only essential features.

11.2 The Cookie Analogy


A helpful analogy for understanding classes and objects:

• Class = Cookie Cutter:The template that defines the shape.

• Instantiate = Making a Cookie:Using the cookie cutter to create an actual cookie.

• Object/Instance = The Cookie:The actual cookie created from the template.

• Properties = Cookie Characteristics:Icing (True/False), Flavor (Lemon/Chocolate).

• Methods = Cookie Actions:Eat(), Bake(), Crumble().

11.3 Encapsulation
Encapsulation combines data and behavior in one package and controls access to internal data:
Public Class BankAccount
' Private field - hidden from outside
Private balance As Decimal

' Public property - controlled access


Public Property AccountBalance() As Decimal
Get
Return balance
End Get
Private Set(value As Decimal)
balance = value
End Set
End Property

' Public method - controlled behavior

Page 26
[Link] Programming - Complete Study Notes

Public Sub Deposit(amount As Decimal)


If amount > 0 Then
balance += amount
End If
End Sub
End Class

Encapsulation protects data integrity by preventing direct modification of internal state. Changes
must go through controlled methods or properties.

11.4 Reusability
One of the biggest advantages of OOP is code reusability:

• Class Libraries:Create classes once, use them in multiple projects.

• Inheritance:Build new classes based on existing ones.

• Components:Create reusable UI and business logic components.

11.5 Multitier Applications


OOP enables the creation of multitier applications where different concerns are separated:

Layer Responsibilities

Presentation Tier (UI) Forms, controls, user interaction, event handling

Business Tier (BLL) Business rules, validation, calculations, logic

Data Tier (DAL) Database connections, queries, data retrieval/storage

Page 27
[Link] Programming - Complete Study Notes

12. Classes and Objects


Classes are the foundation of OOP in [Link]. A class defines the structure and behavior of
objects.

12.1 Creating a Class


To create a class in Visual Studio: Project -> Add Class, then name the class file.
Public Class Student
' Private fields (instance variables)
Private studentId As String
Private studentName As String
Private gpa As Double

' Property Procedures


Public Property Id() As String
Get
Return studentId
End Get
Set(value As String)
studentId = value
End Set
End Property

Public Property Name() As String


Get
Return studentName
End Get
Set(value As String)
If Not [Link](value) Then
studentName = value
End If
End Set
End Property

Public Property GradePointAverage() As Double


Get
Return gpa
End Get
Set(value As Double)
If value >= 0.0 And value <= 4.0 Then
gpa = value
End If
End Set
End Property

' Method
Public Function GetHonorStatus() As String
If gpa >= 3.5 Then
Return "Dean's List"
ElseIf gpa >= 3.0 Then
Return "Honor Roll"
Else
Return "Regular"
End If
End Function
End Class

Page 28
[Link] Programming - Complete Study Notes

12.2 Instantiating Objects


Create objects from classes using the New keyword:
' Declare and instantiate
Dim student1 As New Student()

' Or declare first, then instantiate


Dim student2 As Student
student2 = New Student()

' Set properties


[Link] = "S001"
[Link] = "Alice Johnson"
[Link] = 3.8

' Call methods


Dim status As String = [Link]()
[Link](status) ' "Dean's List"

12.3 Constructors
Constructors are special methods that execute when an object is created. They initialize object state:
Public Class Employee
Private empId As String
Private empName As String
Private salary As Decimal

' Default constructor (no parameters)


Public Sub New()
empId = "E000"
empName = "Unknown"
salary = 0D
End Sub

' Parameterized constructor


Public Sub New(id As String, name As String, initialSalary As Decimal)
empId = id
empName = name
salary = initialSalary
End Sub

' Properties
Public Property Id() As String
Get
Return empId
End Get
Set(value As String)
empId = value
End Set
End Property

Public ReadOnly Property AnnualSalary() As Decimal


Get
Return salary * 12
End Get
End Property
End Class

' Using constructors


Dim emp1 As New Employee() ' Default constructor
Dim emp2 As New Employee("E001", "John Doe", 5000D) ' Parameterized

Page 29
[Link] Programming - Complete Study Notes

12.4 Read-Only and Write-Only Properties


Public Class Product
Private productId As String
Private productName As String
Private createdDate As Date

Public Sub New()


createdDate = [Link] ' Set once in constructor
End Sub

' Read-Write property


Public Property Name() As String
Get
Return productName
End Get
Set(value As String)
productName = value
End Set
End Property

' Read-Only property (no Set)


Public ReadOnly Property Id() As String
Get
Return productId
End Get
End Property

' Write-Only property (no Get)


Public WriteOnly Property InternalCode() As String
Set(value As String)
productId = value
End Set
End Property

' Auto-implemented property (VB 10+)


Public Property Price As Decimal
End Class

12.5 Shared Members


Shared members belong to the class itself, not to individual instances:
Public Class Counter
' Shared field - single copy for all instances
Private Shared instanceCount As Integer = 0

' Instance field - each object has its own copy


Private instanceId As Integer

Public Sub New()


instanceCount += 1
instanceId = instanceCount
End Sub

' Shared property


Public Shared ReadOnly Property TotalInstances() As Integer
Get
Return instanceCount
End Get
End Property

' Instance property


Public ReadOnly Property Id() As Integer

Page 30
[Link] Programming - Complete Study Notes

Get
Return instanceId
End Get
End Property

' Shared method


Public Shared Function GetClassInfo() As String
Return "Counter Class - Tracks instance count"
End Function
End Class

' Access shared members without creating an object


[Link]([Link]())
[Link]([Link])

' Create instances


Dim c1 As New Counter() ' TotalInstances = 1
Dim c2 As New Counter() ' TotalInstances = 2

Shared methods cannot access instance variables (non-shared) because there is no instance. Use
shared members for values that should be shared across all objects of a class.

12.6 The Me Keyword


The Me keyword refers to the current instance of the class:
Public Class Person
Private name As String
Private age As Integer

Public Sub New(name As String, age As Integer)


' Use Me to distinguish between parameter and field
[Link] = name
[Link] = age
End Sub

Public Sub DisplayInfo()


' Me is optional but can improve clarity
[Link]([Link] & " is " & [Link] & " years old")
End Sub
End Class

Page 31
[Link] Programming - Complete Study Notes

13. Inheritance and Polymorphism


Inheritance allows creating new classes from existing ones. Polymorphism enables methods with
the same name to behave differently.

13.1 Inheritance Basics


Inheritance creates a parent-child relationship between classes. The child class inherits all public and
protected members from the parent:
' Base class (Parent)
Public Class Person
Protected name As String
Protected age As Integer

Public Sub New(personName As String, personAge As Integer)


name = personName
age = personAge
End Sub

Public Overridable Function GetInfo() As String


Return name & ", Age: " & age
End Function
End Class

' Derived class (Child)


Public Class Employee
Inherits Person

Private employeeId As String


Private salary As Decimal

Public Sub New(empName As String, empAge As Integer, _n


id As String, empSalary As Decimal)
' Call parent constructor
[Link](empName, empAge)
employeeId = id
salary = empSalary
End Sub

' Override parent method


Public Overrides Function GetInfo() As String
Return [Link]() & ", ID: " & employeeId
End Function

' New method specific to Employee


Public Function CalculateBonus() As Decimal
Return salary * 0.1D
End Function
End Class

13.2 Access Modifiers


Modifier Same Class Derived Class Same Assembly Everywhere

Public Yes Yes Yes Yes

Page 32
[Link] Programming - Complete Study Notes

Protected Yes Yes No No

Friend Yes No Yes No

Protected Friend Yes Yes Yes No

Private Yes No No No

13.3 MyBase Keyword


MyBase refers to the parent class and is used to access parent members:
Public Class Manager
Inherits Employee

Private department As String

Public Sub New(name As String, age As Integer, _n id


As String, salary As Decimal, dept As String)
[Link](name, age, id, salary) ' Call Employee constructor
department = dept
End Sub

Public Overrides Function GetInfo() As String


' Extend parent's GetInfo
Return [Link]() & ", Dept: " & department
End Function
End Class

13.4 Overriding Methods


To override a method, the parent method must be marked Overridable, and the child method must
use Overrides:
' Base class
Public Class Shape
Protected color As String

Public Sub New(shapeColor As String)


color = shapeColor
End Sub

' Mark as overridable


Public Overridable Function GetArea() As Double
Return 0 ' Base implementation
End Function

Public Overridable Function GetDescription() As String


Return "A " & color & " shape"
End Function
End Class

' Derived class


Public Class Circle
Inherits Shape

Private radius As Double

Public Sub New(circleColor As String, r As Double)


[Link](circleColor)
radius = r

Page 33
[Link] Programming - Complete Study Notes

End Sub

' Override base method


Public Overrides Function GetArea() As Double
Return [Link] * radius * radius
End Function

Public Overrides Function GetDescription() As String


Return "A " & color & " circle with radius " & radius
End Function
End Class

13.5 Overloading vs Overriding


Multiple methods in the same class with the same name but different
Overloading
parameter lists (signatures).

A method in a child class that replaces a method in the parent class with the
Overriding
same signature.

' Overloading example (same class, different parameters)


Public Class Calculator
Public Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function

Public Function Add(a As Double, b As Double) As Double


Return a + b
End Function

Public Function Add(a As Integer, b As Integer, c As Integer) As Integer


Return a + b + c
End Function
End Class

' Overriding example (parent and child classes)


Public Class Animal
Public Overridable Sub Speak()
[Link]("Some sound")
End Sub
End Class

Public Class Dog


Inherits Animal

Public Overrides Sub Speak()


[Link]("Woof!")
End Sub
End Class

13.6 MustInherit and MustOverride


MustInherit creates abstract classes that cannot be instantiated directly. MustOverride forces derived
classes to implement the method:
' Abstract base class
Public MustInherit Class Vehicle
Protected make As String
Protected model As String

' Must be implemented by derived classes

Page 34
[Link] Programming - Complete Study Notes

Public MustOverride Function GetDescription() As String

' Regular method


Public Function GetMakeModel() As String
Return make & " " & model
End Function
End Class

' Concrete derived class


Public Class Car
Inherits Vehicle

Private numDoors As Integer

Public Sub New(carMake As String, carModel As String, doors As Integer)


make = carMake
model = carModel
numDoors = doors
End Sub

' Must implement abstract method


Public Overrides Function GetDescription() As String
Return numDoors & "-door " & GetMakeModel()
End Function
End Class

13.7 Garbage Collection


The .NET Garbage Collector automatically manages memory by cleaning up unused objects:

• Automatic Cleanup:Periodically checks for unreferenced objects and releases memory.

• No Manual Management:Unlike C/C++, you don't need to explicitly free memory.

• Finalize Method:Can be overridden for cleanup, but generally not recommended.


' Garbage collection happens automatically
Dim obj As New LargeObject()
[Link]()
obj = Nothing ' Remove reference (optional hint to GC)

' Force garbage collection (rarely needed)


[Link]()

Page 35
[Link] Programming - Complete Study Notes

14. Database Connectivity with [Link]


[Link] (ActiveX Data Objects for .NET) is a set of classes for accessing and manipulating data
in databases.

14.1 Key [Link] Components


Component Description

SqlConnection Establishes connection to SQL Server database

SqlCommand Executes SQL queries and stored procedures

SqlDataReader Reads data from database in forward-only stream

DataSet In-memory cache of data from multiple tables

DataTable In-memory representation of a single database table

SqlDataAdapter Bridge between DataSet and database for retrieving/updating data

SqlTransaction Manages database transactions for data integrity

14.2 Database Connection


Imports [Link]

Public Class DatabaseConnection


' Connection string for SQL Server
Private connectionString As String = _n
"Server=YOUR_SERVER;Database=YOUR_DB;"
Private connectionString2 As String = _n
"Server=YOUR_SERVER;Database=YOUR_DB;" & _n "User
Id=username;Password=password;"
Private connectionString3 As String = _n
"Server=YOUR_SERVER;Database=YOUR_DB;" & _n "Integrated
Security=True;" ' Windows auth

Public Function GetConnection() As SqlConnection


Return New SqlConnection(connectionString)
End Function

Public Sub TestConnection()


Using conn As New SqlConnection(connectionString)
Try
[Link]()
[Link]("Connection successful!")
Catch ex As Exception
[Link]("Error: " & [Link])
Finally
If [Link] = [Link] Then
[Link]()
End If
End Try
End Using
End Sub
End Class

Page 36
[Link] Programming - Complete Study Notes

14.3 Executing SQL Queries


' INSERT Example
Public Sub AddProduct(productName As String, price As Decimal)
Dim query As String = "INSERT INTO Products (ProductName, Price) "
query &= "VALUES (@Name, @Price)"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
' Add parameters (prevents SQL injection)
[Link]("@Name", productName)
[Link]("@Price", price)

[Link]()
[Link]()
End Using
End Using
End Sub

' UPDATE Example


Public Sub UpdatePrice(productId As Integer, newPrice As Decimal)
Dim query As String = "UPDATE Products SET Price = @Price "
query &= "WHERE ProductID = @Id"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
[Link]("@Price", newPrice)
[Link]("@Id", productId)

[Link]()
Dim rowsAffected As Integer = [Link]()
[Link](rowsAffected & " rows updated")
End Using
End Using
End Sub

' DELETE Example


Public Sub DeleteProduct(productId As Integer)
Dim query As String = "DELETE FROM Products WHERE ProductID = @Id"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
[Link]("@Id", productId)

[Link]()
[Link]()
End Using
End Using
End Sub

14.4 Retrieving Data with DataReader


Public Sub DisplayAllProducts()
Dim query As String = "SELECT * FROM Products"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
[Link]()
Using reader As SqlDataReader = [Link]()
While [Link]()
' Access columns by name or index
[Link](reader("ProductName") & " - $" & _n
reader("Price"))
End While

Page 37
[Link] Programming - Complete Study Notes

End Using
End Using
End Using
End Sub

Public Function GetProductList() As List(Of String)


Dim products As New List(Of String)
Dim query As String = "SELECT ProductName FROM Products"

Using conn As New SqlConnection(connectionString)


Using cmd As New SqlCommand(query, conn)
[Link]()
Using reader As SqlDataReader = [Link]()
While [Link]()
[Link]([Link](0))
End While
End Using
End Using
End Using

Return products
End Function

14.5 Using DataSet and DataAdapter


Public Function GetAllProducts() As DataTable
Dim query As String = "SELECT * FROM Products"
Dim ds As New DataSet()

Using conn As New SqlConnection(connectionString)


Dim adapter As New SqlDataAdapter(query, conn)
[Link](ds, "Products")
End Using

Return [Link]("Products")
End Function

' Bind to DataGridView


Private Sub LoadProducts()
Dim dt As DataTable = GetAllProducts()
[Link] = dt
End Sub

14.6 Database Transactions


Public Sub TransferFunds(fromAccount As String, toAccount As String, amount
As Decimal)
Using conn As New SqlConnection(connectionString)
[Link]()
Dim transaction As SqlTransaction = [Link]()

Try
' Deduct from source account
Dim cmd1 As New SqlCommand(_n "UPDATE Accounts
SET Balance = Balance - @Amount "
& "WHERE AccountNumber = @FromAcct", conn, transaction)
[Link]("@Amount", amount)
[Link]("@FromAcct", fromAccount)
[Link]()

' Add to destination account


Dim cmd2 As New SqlCommand(_n "UPDATE Accounts
SET Balance = Balance + @Amount "
& "WHERE AccountNumber = @ToAcct", conn, transaction)

Page 38
[Link] Programming - Complete Study Notes

[Link]("@Amount", amount)
[Link]("@ToAcct", toAccount)
[Link]()

' Commit if both succeed


[Link]()
[Link]("Transfer successful")

Catch ex As Exception
' Rollback on error
[Link]()
[Link]("Transfer failed: " & [Link])
End Try
End Using
End Sub

Always use parameters (AddWithValue) instead of string concatenation to prevent SQL injection
attacks. Never trust user input!

Page 39
[Link] Programming - Complete Study Notes

15. Debugging Techniques


Debugging is the process of finding and fixing errors in your code. Visual Studio provides
powerful debugging tools.

15.1 Types of Errors


Syntax Errors Code that violates [Link] rules. Caught by the compiler before running.

Runtime Errors Errors that occur while the program is running (exceptions).

Logic Errors Code runs but produces incorrect results. Hardest to find.

15.2 Setting Breakpoints


Breakpoints pause program execution at a specific line, allowing you to inspect the program state:

• Set Breakpoint:Click in the gray left margin or press F9 on the line.

• Remove Breakpoint:Click the red dot in the margin or press F9 again.

• Disable Breakpoint:Right-click and select Disable Breakpoint.

15.3 Stepping Through Code


Step Into (F11) Execute the current line and step into any called procedures.

Step Over (F10) Execute the current line without stepping into called procedures.

Step Out (Shift+F11) Execute remaining lines in current procedure and return to caller.

Continue (F5) Resume execution until next breakpoint or program end.

15.4 Debug Windows

Locals Window
Shows values of all local variables in the current scope. Automatically updates as you step through
code.

Autos Window
Automatically shows variables used in the previous and next few lines of code. Useful for focusing on
relevant variables.

Watch Window
Add specific variables or expressions to monitor their values throughout debugging.

Page 40
[Link] Programming - Complete Study Notes

Immediate Window
Execute [Link] statements and evaluate expressions during debugging.

15.5 Writing to Output Window


' Add Imports [Link] at top

' Write debug messages


[Link]("Button clicked")
[Link]("Value of x: " & x)

' Write only if condition is true


[Link](x > 100, "x exceeded 100")

' Write to trace (available in release builds too)


[Link]("Application started")

15.6 Inspecting Variables


• Hover Mouse:Place mouse pointer over any variable to see its current value.

• Quick Watch:Right-click variable and select QuickWatch to view in dialog.

• Add Watch:Right-click variable and select Add Watch to monitor continuously.

15.7 Exception Handling


Try
' Code that might cause an error
Dim result As Integer = 100 \\ divisor

Catch ex As DivideByZeroException
' Handle specific exception
[Link]("Cannot divide by zero!")

Catch ex As FormatException
' Handle format errors
[Link]("Invalid number format")

Catch ex As Exception
' Handle any other exception
[Link]("Error: " & [Link])

Finally
' Always executes (cleanup code)
[Link]("Operation completed")
End Try

15.8 Debugging Tips


18. Start Small:Test small pieces of code before integrating.

19. Use Breakpoints:Set breakpoints at key locations to trace execution flow.

20. Check Variable Values:Verify variables contain expected values at each step.

21. Read Error Messages:Exception messages often indicate the exact problem.

Page 41
[Link] Programming - Complete Study Notes

22. Use Output Window:Add [Link] statements to trace program flow.

23. Step Through Code:Use F10 and F11 to execute code line by line.

Good debugging skills are essential for any programmer. Practice using the debugger regularly to
become proficient at finding and fixing errors.

Page 42

You might also like