Introduction to Visual Basic .NET & Setup
What is Visual Basic .NET?
Visual Basic .NET (VB.NET) is a modern, object-oriented programming language from Microsoft. It is easy to learn, highly productive, and tightly integrated with the .NET ecosystem. It is widely used for Windows desktop applications, business tools, and enterprise software.
VB.NET was designed to help developers create applications quickly using simple and readable syntax. It combines the simplicity of traditional Visual Basic with the power of the modern .NET framework.
VB.NET supports object-oriented programming concepts such as classes, inheritance, encapsulation, and polymorphism, making it suitable for both beginners and professional developers.
Why Learn VB.NET?
- Very readable, English-like syntax
- Rapid Application Development (RAD)
- Excellent Windows Forms and WPF support
- Seamless integration with C# and the .NET platform
- Strong support from Microsoft
- Great for desktop and business applications
- Easy transition into other .NET languages
Where is VB.NET Used?
- Windows desktop applications
- Business management systems
- Database-driven software
- Enterprise tools and utilities
- Automation applications
- Educational and academic projects
Understanding the .NET Framework
The .NET framework is a software development platform created by Microsoft that provides tools, libraries, and runtime support for building applications.
VB.NET runs on the .NET platform, which provides:
- Built-in libraries and APIs
- Memory management through garbage collection
- Security and exception handling
- Support for multiple programming languages
Languages such as VB.NET and C# can work together because they use the same .NET framework.
Setup
Install Visual Studio Community (free) from visualstudio.microsoft.com. Choose the ".NET desktop development" workload.
Visual Studio is Microsoft's official Integrated Development Environment (IDE) used for writing, testing, debugging, and running VB.NET applications.
Steps to Install Visual Studio
- Download Visual Studio Community Edition
- Run the installer
- Select the ".NET desktop development" workload
- Complete the installation process
- Launch Visual Studio
Creating Your First VB.NET Project
- Open Visual Studio
- Click Create a new project
- Select Console App (.NET)
- Choose Visual Basic as the language
- Enter a project name
- Click Create
Visual Studio automatically generates starter code for your first application.
Understanding the First Program
Module Module1 Sub Main() Console.WriteLine("Hello, Visual Basic .NET Mastery!") Console.ReadKey() End Sub End Module
Code Explanation
Moduledefines a program container.Sub Main()is the starting point of the application.Console.WriteLine()displays output on the screen.Console.ReadKey()waits for a key press before closing the program.End Submarks the end of the procedure.
๐ป Try It Yourself - Multi-Language Compiler
Practice Visual Basic and many other programming languages right here in your browser! Switch between languages, modify the code, and click "Run" to see results instantly.
๐ก Practice Tips:
- Switch to Visual Basic in the language selector and try Windows form examples
- Experiment with VB.NET's event-driven programming and .NET framework features
- Try other .NET languages like C#, F#, or compare with desktop development concepts
- Use the "Load Example" button to see Visual Basic-specific code samples
- Use Ctrl+Enter to quickly run your code
Running a Program
You can run VB.NET programs using the following methods:
- Press
F5to run with debugging - Press
Ctrl + F5to run without debugging - Click the Start button in Visual Studio
Debugging helps developers identify and fix errors in programs.
Console Applications
A console application displays output in a command-line window.
Console applications are ideal for beginners because they focus on programming logic without requiring graphical interfaces.
Module Program Sub Main() Console.WriteLine("Welcome to VB.NET") Console.WriteLine("Learning programming is fun!") Console.ReadKey() End Sub End Module
Important Notes for Beginners
- VB.NET keywords are not case-sensitive.
- Always save projects in organized folders.
- Use meaningful project and file names.
- Practice typing programs manually to improve learning.
- Read error messages carefully while debugging.
Common VB.NET Keywords
| Keyword | Description |
|---|---|
Module |
Defines a module container |
Sub |
Defines a procedure |
End |
Marks the end of a block |
Console.WriteLine() |
Displays output |
Console.ReadKey() |
Waits for keyboard input |
Create a new Console Application in Visual Studio. Modify it to print your name and run the project (F5).
Create a program that displays your city, favorite subject, and hobby using multiple
Console.WriteLine() statements.
Practice creating and running multiple console applications in Visual Studio.
Variables & Data Types
What are Variables?
Variables are used to store data in memory while a program is running. They allow programmers to save values and use them later in calculations, conditions, and other operations.
In VB.NET, every variable has:
- A name
- A data type
- A stored value
Variables make programs dynamic because values can change during execution.
Declaring Variables
In VB.NET, variables are declared using the Dim keyword.
Dim age As Integer Dim name As String Dim salary As Double
Here:
agestores whole numbers.namestores text.salarystores decimal numbers.
Assigning Values to Variables
After declaring variables, values can be assigned using the assignment operator =.
Dim age As Integer age = 21 Dim city As String city = "London"
You can also declare and assign values in a single line.
Dim marks As Integer = 95 Dim studentName As String = "Alex"
Common Data Types in VB.NET
VB.NET provides different data types for storing different kinds of information.
| Data Type | Description | Example |
|---|---|---|
Integer |
Stores whole numbers | 10 |
Double |
Stores decimal numbers | 12.5 |
String |
Stores text | "Hello" |
Boolean |
Stores True or False | True |
Char |
Stores a single character | "A" |
Displaying Variable Values
Use Console.WriteLine() to display variable values on the screen.
Dim name As String = "John" Dim age As Integer = 22 Console.WriteLine(name) Console.WriteLine(age)
Combining Text and Variables
VB.NET allows text and variables to be combined using the & operator.
Dim name As String = "Emma"
Dim marks As Integer = 90
Console.WriteLine("Student Name: " & name)
Console.WriteLine("Marks: " & marks)
Rules for Naming Variables
- Variable names must begin with a letter.
- Spaces are not allowed.
- Special characters are not allowed except underscores.
- Use meaningful variable names.
- VB.NET keywords should not be used as variable names.
' Valid variable names Dim totalMarks As Integer Dim student_name As String ' Invalid variable names ' Dim 2marks As Integer ' Dim student name As String
Understanding Constants
Constants store fixed values that cannot be changed during program execution.
Const PI As Double = 3.14159
Constants improve readability and prevent accidental value changes.
User Input in VB.NET
Programs can accept input from users using Console.ReadLine().
Dim username As String
Console.Write("Enter your name: ")
username = Console.ReadLine()
Console.WriteLine("Hello " & username)
Console.ReadLine() reads text entered by the user.
Type Conversion
Sometimes data must be converted from one type to another.
Dim number As Integer
number = Convert.ToInt32("100")
Console.WriteLine(number)
The Convert class helps convert values between data types.
Variable Scope
The scope of a variable determines where it can be accessed in a program.
- Local variables exist only inside procedures.
- Global variables can be accessed throughout the module.
Module Module1 Dim globalValue As Integer = 100 Sub Main() Dim localValue As Integer = 50 Console.WriteLine(globalValue) Console.WriteLine(localValue) End Sub End Module
Important Notes for Beginners
- Always initialize variables before using them.
- Use meaningful names for better readability.
- Choose appropriate data types for storing values.
- Constants are useful for fixed values.
- Practice using user input and output frequently.
Create variables to store your name, age, and favorite color. Display them using
Console.WriteLine().
Create a program that accepts user input for marks and displays the result.
Create constants for PI and gravity and display their values.
Create variables using different data types such as Integer, Double, String, and Boolean.
Operators & Expressions
What are Operators?
Operators are symbols used to perform operations on variables and values. VB.NET provides different types of operators for mathematical calculations, comparisons, and logical decisions.
Operators are commonly used in:
- Calculations
- Conditions
- Loops
- Decision-making statements
What are Expressions?
An expression is a combination of variables, values, and operators that produces a result.
Dim result As Integer result = 10 + 5
In this example:
10 + 5is an expression.- The expression evaluates to
15.
Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
| Operator | Description | Example |
|---|---|---|
+ |
Addition | a + b |
- |
Subtraction | a - b |
* |
Multiplication | a * b |
/ |
Division | a / b |
\ |
Integer Division | 10 \ 3 |
Mod |
Returns remainder | 10 Mod 3 |
Dim a As Integer = 10 Dim b As Integer = 3 Console.WriteLine(a + b) Console.WriteLine(a - b) Console.WriteLine(a * b) Console.WriteLine(a / b) Console.WriteLine(a \ b) Console.WriteLine(a Mod b)
Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Description |
|---|---|
= |
Assigns a value |
+= |
Add and assign |
-= |
Subtract and assign |
Dim x As Integer = 10 x += 5 Console.WriteLine(x) x -= 2 Console.WriteLine(x)
Comparison Operators
Comparison operators compare two values and return either True or
False.
| Operator | Description |
|---|---|
= |
Equal to |
<> |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Dim num1 As Integer = 10 Dim num2 As Integer = 20 Console.WriteLine(num1 = num2) Console.WriteLine(num1 < num2) Console.WriteLine(num1 > num2)
Logical Operators
Logical operators combine multiple conditions.
| Operator | Description |
|---|---|
And |
True if both conditions are true |
Or |
True if at least one condition is true |
Not |
Reverses the logical result |
Dim age As Integer = 25 Console.WriteLine(age > 18 And age < 60) Console.WriteLine(age < 18 Or age > 60) Console.WriteLine(Not(age = 25))
String Concatenation
Strings can be combined using the & operator.
Dim firstName As String = "John" Dim lastName As String = "Smith" Dim fullName As String fullName = firstName & " " & lastName Console.WriteLine(fullName)
Operator Precedence
VB.NET follows precedence rules while evaluating expressions.
- Parentheses
- Exponentiation
- Multiplication and Division
- Addition and Subtraction
- Comparison Operators
- Logical Operators
Dim result1 As Integer = 2 + 3 * 4 Dim result2 As Integer = (2 + 3) * 4 Console.WriteLine(result1) Console.WriteLine(result2)
Parentheses improve readability and help avoid unexpected results.
Using Built-in Mathematical Functions
VB.NET provides built-in methods for mathematical calculations.
Console.WriteLine(Math.Sqrt(25)) Console.WriteLine(Math.Pow(2, 3)) Console.WriteLine(Math.Abs(-10))
Math.Sqrt()calculates square roots.Math.Pow()calculates powers.Math.Abs()returns absolute values.
Important Notes for Beginners
- Use parentheses to make expressions easier to understand.
- Practice arithmetic and logical operations regularly.
- Comparison operators return Boolean values.
- Logical operators are important in conditions and loops.
- Understand operator precedence to avoid errors.
Create a program that performs addition, subtraction, multiplication, and division on two numbers.
Use comparison operators to compare two integer values and display the results.
Create expressions using parentheses and observe how operator precedence changes results.
Create a program that combines first name and last name using string concatenation.
Control Flow
What is Control Flow?
Control flow determines how a VB.NET program executes different parts of code based on conditions, decisions, and repetition. It controls the order in which statements are executed.
Without control flow, programs would execute every line sequentially without making decisions.
Control flow allows programs to:
- Make decisions based on conditions
- Repeat tasks automatically
- Respond differently to user input
- Control program execution efficiently
Conditional Statements
Conditional statements allow programs to execute specific code only when certain conditions are true.
The If Statement
The If statement checks a condition and executes code if the condition is true.
Dim age As Integer = 20 If age >= 18 Then Console.WriteLine("You are eligible to vote.") End If
If the condition evaluates to True, the code inside the block executes.
If...Else Statement
The If...Else statement provides an alternative block of code when the condition is
false.
Dim marks As Integer = 45 If marks >= 50 Then Console.WriteLine("Pass") Else Console.WriteLine("Fail") End If
If...ElseIf...Else Statement
Use ElseIf when multiple conditions need to be checked.
Dim number As Integer = 0 If number > 0 Then Console.WriteLine("Positive") ElseIf number < 0 Then Console.WriteLine("Negative") Else Console.WriteLine("Zero") End If
Conditions are checked from top to bottom until one becomes true.
Nested If Statements
An If statement can be placed inside another If statement.
Dim number As Integer = 8 If number > 0 Then If number Mod 2 = 0 Then Console.WriteLine("Positive Even Number") Else Console.WriteLine("Positive Odd Number") End If End If
The Mod operator returns the remainder after division.
Select Case Statement
The Select Case statement is useful when comparing one variable against multiple
possible values.
Dim day As Integer = 3 Select Case day Case 1 Console.WriteLine("Monday") Case 2 Console.WriteLine("Tuesday") Case 3 Console.WriteLine("Wednesday") Case Else Console.WriteLine("Invalid Day") End Select
Select Case improves readability when handling many possible options.
Introduction to Loops
Loops allow programs to repeat a block of code multiple times automatically.
VB.NET mainly provides:
- For Loop
- While Loop
- Do While Loop
For Loop
A For loop is used when the number of repetitions is known.
For i As Integer = 1 To 5 Console.WriteLine(i) Next
For Loop with Step
The Step keyword changes the increment value.
For i As Integer = 0 To 10 Step 2 Console.WriteLine(i) Next
While Loop
A While loop repeats while a condition remains true.
Dim x As Integer = 1 While x <= 5 Console.WriteLine(x) x += 1 End While
Be careful because incorrect conditions may create infinite loops.
Do While Loop
The Do While loop executes code repeatedly while a condition is true.
Dim number As Integer = 1 Do While number <= 5 Console.WriteLine(number) number += 1 Loop
Nested Loops
Loops can also be placed inside other loops.
For i As Integer = 1 To 3 For j As Integer = 1 To 2 Console.WriteLine(i & " " & j) Next Next
Nested loops are commonly used in tables, patterns, and matrix-like operations.
Exit Statement
The Exit statement immediately stops a loop.
For i As Integer = 1 To 10 If i = 5 Then Exit For End If Console.WriteLine(i) Next
Continue Statement
The Continue statement skips the current iteration and moves to the next one.
For i As Integer = 1 To 5 If i = 3 Then Continue For End If Console.WriteLine(i) Next
In this example, the value 3 is skipped.
Important Notes for Beginners
- Always close blocks correctly using
End If,Next, orLoop. - Use indentation to improve readability.
Forloops are best when repetitions are fixed.Whileloops are useful when repetition depends on conditions.- Test conditions carefully to avoid infinite loops.
Create a program that checks whether a number is positive, negative, or zero.
Create a For loop that displays numbers from 1 to 20.
Create a While loop that displays even numbers from 2 to 10.
Use a Select Case statement to display the name of a month based on a number.
Create a nested loop that displays multiplication tables from 1 to 5.
Loops
What are Loops?
Loops are programming structures that allow a block of code to execute repeatedly until a condition becomes false. They help reduce repetitive code and make programs more efficient.
Loops are commonly used for:
- Displaying repeated output
- Processing collections of data
- Performing calculations multiple times
- Automating repetitive tasks
VB.NET provides several types of loops for different situations.
Types of Loops in VB.NET
- For Loop
- While Loop
- Do While Loop
- Do Until Loop
- For Each Loop
For Loop
A For loop is used when the number of repetitions is known in advance.
For i As Integer = 1 To 5 Console.WriteLine(i) Next
The loop variable automatically increases after each iteration.
For Loop with Step
The Step keyword controls the increment or decrement value.
For i As Integer = 0 To 10 Step 2 Console.WriteLine(i) Next
Reverse Loop
A negative step value can create reverse loops.
For i As Integer = 5 To 1 Step -1 Console.WriteLine(i) Next
While Loop
A While loop repeats as long as the condition remains true.
Dim number As Integer = 1 While number <= 5 Console.WriteLine(number) number += 1 End While
The condition is checked before executing the loop body.
Do While Loop
The Do While loop also repeats while a condition is true.
Dim x As Integer = 1 Do While x <= 5 Console.WriteLine(x) x += 1 Loop
This loop behaves similarly to the While loop.
Do Until Loop
The Do Until loop continues until a condition becomes true.
Dim value As Integer = 1 Do Until value > 5 Console.WriteLine(value) value += 1 Loop
The loop stops once the condition becomes true.
For Each Loop
The For Each loop is used to iterate through collections and arrays.
Dim numbers() As Integer = {1, 2, 3, 4, 5}
For Each num As Integer In numbers
Console.WriteLine(num)
Next
For Each loops are simpler and safer when working with collections.
Nested Loops
Loops can be placed inside other loops. These are called nested loops.
For i As Integer = 1 To 3 For j As Integer = 1 To 2 Console.WriteLine(i & " " & j) Next Next
Nested loops are useful for patterns, tables, and matrix-style operations.
Exit Statements
The Exit statement immediately terminates a loop.
For i As Integer = 1 To 10 If i = 5 Then Exit For End If Console.WriteLine(i) Next
The loop stops completely when the condition is met.
Continue Statements
The Continue statement skips the current iteration and moves to the next one.
For i As Integer = 1 To 5 If i = 3 Then Continue For End If Console.WriteLine(i) Next
In this example, the value 3 is skipped.
Infinite Loops
An infinite loop occurs when the loop condition never becomes false.
' Infinite loop example While True Console.WriteLine("Running forever") End While
Infinite loops can freeze programs if not handled properly.
Looping Through Arrays
Loops are commonly used with arrays.
Dim fruits() As String = {"Apple", "Banana", "Mango"}
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
Best Practices for Loops
- Use meaningful loop variable names.
- Avoid unnecessary nested loops.
- Ensure loop conditions eventually become false.
- Use
For Eachfor collections whenever possible. - Indent loop code properly for readability.
Important Notes for Beginners
Forloops are best for fixed repetitions.Whileloops are useful when repetitions depend on conditions.- Nested loops increase complexity, so use them carefully.
- Always test loop conditions carefully.
- Practice loops regularly to improve problem-solving skills.
Create a For loop that displays numbers from 1 to 50.
Create a While loop that displays even numbers from 2 to 20.
Create a multiplication table using nested loops.
Create an array of names and display them using a For Each loop.
Create a reverse counting program using a negative Step value.
Procedures & Functions
Procedures and functions are essential building blocks in Visual Basic programming. They help organize code into reusable sections, making programs easier to read, maintain, and debug.
Instead of writing the same code repeatedly, developers can create procedures and functions that can be called whenever needed. This improves efficiency and reduces code duplication.
What are Procedures?
A procedure is a block of code that performs a specific task.
In Visual Basic, procedures are commonly created using the Sub keyword.
Sub procedures do not return a value. They are mainly used for performing actions such as displaying messages, processing data, or handling user input.
Sub Procedures
Sub Greet(name As String)
Console.WriteLine("Hello, " & name)
End Sub
Greet("Ahmed")
In this example:
- Sub Greet defines a new procedure
- name As String is a parameter
- Console.WriteLine() displays output
- Greet("Ahmed") calls the procedure
Output:
Hello, Ahmed
Why Use Procedures?
- Reduce duplicate code
- Improve program organization
- Make debugging easier
- Increase code reusability
- Simplify large applications
Passing Parameters
Parameters allow information to be passed into procedures and functions. They make code flexible and reusable.
Sub DisplayMessage(message As String)
Console.WriteLine(message)
End Sub
DisplayMessage("Welcome to VB.NET")
What are Functions?
Functions are similar to procedures, but they return a value after performing calculations or processing data.
Functions are declared using the Function keyword.
Functions
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Dim total As Integer = Add(5, 3) ' 8
In this example:
- Add() is a function
- a and b are parameters
- As Integer defines the return type
- Return sends the result back
Output:
8
Difference Between Sub and Function
| Sub Procedure | Function |
|---|---|
| Does not return a value | Returns a value |
| Used for actions | Used for calculations |
| Declared with Sub | Declared with Function |
Return Values
Functions return values using the Return keyword.
Function Square(num As Integer) As Integer
Return num * num
End Function
Console.WriteLine(Square(4))
Output:
16
Optional Parameters
Optional parameters allow arguments to be omitted when calling procedures or functions. Default values are used automatically.
Optional & ByRef
Sub Greet(Optional name As String = "World")
Console.WriteLine("Hello, " & name)
End Sub
Sub Swap(ByRef a As Integer, ByRef b As Integer)
Dim tmp = a
a = b
b = tmp
End Sub
In this example:
- Optional allows a default parameter value
- ByRef passes variables by reference
- Changes made inside the procedure affect original variables
ByVal vs ByRef
Visual Basic supports two ways of passing parameters:
- ByVal โ Passes a copy of the value
- ByRef โ Passes the original variable reference
Sub ChangeValue(ByVal num As Integer)
num = 100
End Sub
Changes inside a ByVal parameter do not affect the original variable.
Function Overloading
Visual Basic allows multiple functions with the same name but different parameter lists. This is called function overloading.
Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function
Function Multiply(a As Double, b As Double) As Double
Return a * b
End Function
Recursive Functions
A recursive function calls itself repeatedly until a condition is met. Recursion is useful for mathematical and algorithmic problems.
Function Factorial(n As Integer) As Integer
If n = 0 Then
Return 1
End If
Return n * Factorial(n - 1)
End Function
Variable Scope
Scope determines where variables can be accessed inside a program.
- Local Variables โ Accessible only inside procedures
- Global Variables โ Accessible throughout the program
Dim globalVar As Integer = 10
Sub Test()
Dim localVar As Integer = 5
End Sub
Error Handling in Functions
Functions and procedures should handle invalid input properly to avoid crashes.
Try
Dim result = 10 / 0
Catch ex As Exception
Console.WriteLine("Error occurred")
End Try
Advantages of Functions & Procedures
- Improve code reusability
- Reduce program complexity
- Make code easier to maintain
- Increase readability
- Simplify debugging and testing
Real-World Applications
- Banking systems
- Game development
- Desktop applications
- Inventory management software
- Student management systems
- Scientific applications
Best Practices
- Use meaningful procedure and function names
- Keep functions short and focused
- Avoid duplicate code
- Use comments for complex logic
- Validate user input properly
Write functions to compute factorial, GCD, and Fibonacci numbers.
Try adding:
- User input handling
- Error checking
- Recursive implementations
- Loop-based solutions
Summary
In this lecture, we learned how procedures and functions work in Visual Basic. We explored Sub procedures, functions, parameters, optional arguments, recursion, and parameter passing methods.
Functions and procedures are essential programming concepts that improve organization, reusability, and maintainability in software development.
Arrays & Collections
Arrays and collections are essential data structures in Visual Basic programming. They allow developers to store, organize, and manage multiple values efficiently.
Instead of creating separate variables for every piece of data, arrays and collections group related data together. This makes programs more scalable, readable, and easier to maintain.
Introduction to Arrays
An array is a collection of values stored inside a single variable. All elements inside an array usually share the same data type.
Arrays are useful when working with lists of numbers, names, scores, products, or other grouped data.
Arrays
Dim nums(4) As Integer ' 0-4 = 5 elements
nums(0) = 10
Dim names() As String = {"Aman", "Rahul", "Arjun"}
For Each n As String In names
Console.WriteLine(n)
Next
In this example:
- nums(4) creates an array with 5 elements
- Array indexing starts from 0
- names() initializes a string array
- For Each loops through all elements
Output:
Aman Rahul Arjun
Why Use Arrays?
- Store multiple values efficiently
- Reduce repetitive variables
- Simplify loops and processing
- Improve code organization
- Useful for large datasets
Accessing Array Elements
Array elements are accessed using indexes inside parentheses.
Dim fruits() As String = {"Apple", "Banana", "Orange"}
Console.WriteLine(fruits(1))
Output:
Banana
Here, fruits(1) accesses the second element because indexing begins at 0.
Modifying Array Values
Array elements can be updated by assigning new values.
Dim scores() As Integer = {50, 60, 70}
scores(1) = 95
Console.WriteLine(scores(1))
Looping Through Arrays
Loops are commonly used with arrays to process all elements efficiently.
Dim nums() As Integer = {1, 2, 3, 4, 5}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next
The Length property returns the total number of elements in the array.
Multi-Dimensional Arrays
Visual Basic supports arrays with multiple dimensions such as rows and columns.
Dim matrix(1, 1) As Integer matrix(0, 0) = 10 matrix(0, 1) = 20 matrix(1, 0) = 30 matrix(1, 1) = 40
Multi-dimensional arrays are useful for tables, matrices, and grid-based systems.
Introduction to Collections
Collections are advanced data structures that provide more flexibility than arrays. Unlike arrays, collections can dynamically grow and shrink during program execution.
List(Of T)
The List(Of T) collection stores dynamic lists of data.
It is one of the most commonly used collection types in VB.NET.
Dim items As New List(Of String)
items.Add("Apple")
items.Add("Banana")
items.Remove("Apple")
Console.WriteLine(items.Count)
In this example:
- Add() inserts new items
- Remove() deletes items
- Count returns total items
Output:
1
Advantages of List(Of T)
- Dynamic resizing
- Easy insertion and removal
- Powerful built-in methods
- Efficient data handling
- Flexible compared to arrays
Looping Through Lists
Dim colors As New List(Of String)
colors.Add("Red")
colors.Add("Blue")
colors.Add("Green")
For Each c In colors
Console.WriteLine(c)
Next
Dictionary
A Dictionary stores data as key-value pairs. It allows fast searching and retrieval using keys.
Dim ages As New Dictionary(Of String, Integer)
ages("Ahmed") = 25
ages("Sara") = 30
For Each kvp In ages
Console.WriteLine($"{kvp.Key}: {kvp.Value}")
Next
In this example:
- Ahmed and Sara are keys
- 25 and 30 are values
- kvp.Key accesses the key
- kvp.Value accesses the value
Accessing Dictionary Values
Console.WriteLine(ages("Ahmed"))
Output:
25
Checking Dictionary Keys
The ContainsKey() method checks whether a key exists.
If ages.ContainsKey("Sara") Then
Console.WriteLine("Found")
End If
Choosing Between Arrays & Collections
| Arrays | Collections |
|---|---|
| Fixed size | Dynamic size |
| Faster for simple data | More flexible |
| Less memory overhead | More built-in features |
Real-World Applications
- Student management systems
- Phone books and contact lists
- Inventory systems
- Game scoreboards
- Banking applications
- Shopping cart systems
Best Practices
- Use arrays for fixed-size data
- Use lists for dynamic data
- Use dictionaries for fast key-based lookup
- Choose meaningful variable names
- Validate indexes before accessing elements
Build a phone book using Dictionary(Of String, String).
Try adding:
- Add new contacts
- Search contacts by name
- Delete contacts
- Display all saved entries
Summary
In this lecture, we learned about arrays and collections in Visual Basic. We explored arrays, lists, dictionaries, looping techniques, and data storage methods.
Arrays and collections are essential tools for organizing and processing data efficiently in modern applications.
Arrays & Collections
Arrays and collections are essential data structures in Visual Basic programming. They allow developers to store, organize, and manage multiple values efficiently.
Instead of creating separate variables for every piece of data, arrays and collections group related data together. This makes programs more scalable, readable, and easier to maintain.
Introduction to Arrays
An array is a collection of values stored inside a single variable. All elements inside an array usually share the same data type.
Arrays are useful when working with lists of numbers, names, scores, products, or other grouped data.
Arrays
Dim nums(4) As Integer ' 0-4 = 5 elements
nums(0) = 10
Dim names() As String = {"Aman", "Rahul", "Arjun"}
For Each n As String In names
Console.WriteLine(n)
Next
In this example:
- nums(4) creates an array with 5 elements
- Array indexing starts from 0
- names() initializes a string array
- For Each loops through all elements
Output:
Aman Rahul Arjun
Why Use Arrays?
- Store multiple values efficiently
- Reduce repetitive variables
- Simplify loops and processing
- Improve code organization
- Useful for large datasets
Accessing Array Elements
Array elements are accessed using indexes inside parentheses.
Dim fruits() As String = {"Apple", "Banana", "Orange"}
Console.WriteLine(fruits(1))
Output:
Banana
Here, fruits(1) accesses the second element because indexing begins at 0.
Modifying Array Values
Array elements can be updated by assigning new values.
Dim scores() As Integer = {50, 60, 70}
scores(1) = 95
Console.WriteLine(scores(1))
Looping Through Arrays
Loops are commonly used with arrays to process all elements efficiently.
Dim nums() As Integer = {1, 2, 3, 4, 5}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next
The Length property returns the total number of elements in the array.
Multi-Dimensional Arrays
Visual Basic supports arrays with multiple dimensions such as rows and columns.
Dim matrix(1, 1) As Integer matrix(0, 0) = 10 matrix(0, 1) = 20 matrix(1, 0) = 30 matrix(1, 1) = 40
Multi-dimensional arrays are useful for tables, matrices, and grid-based systems.
Introduction to Collections
Collections are advanced data structures that provide more flexibility than arrays. Unlike arrays, collections can dynamically grow and shrink during program execution.
List(Of T)
The List(Of T) collection stores dynamic lists of data.
It is one of the most commonly used collection types in VB.NET.
Dim items As New List(Of String)
items.Add("Apple")
items.Add("Banana")
items.Remove("Apple")
Console.WriteLine(items.Count)
In this example:
- Add() inserts new items
- Remove() deletes items
- Count returns total items
Output:
1
Advantages of List(Of T)
- Dynamic resizing
- Easy insertion and removal
- Powerful built-in methods
- Efficient data handling
- Flexible compared to arrays
Looping Through Lists
Dim colors As New List(Of String)
colors.Add("Red")
colors.Add("Blue")
colors.Add("Green")
For Each c In colors
Console.WriteLine(c)
Next
Dictionary
A Dictionary stores data as key-value pairs. It allows fast searching and retrieval using keys.
Dim ages As New Dictionary(Of String, Integer)
ages("Ahmed") = 25
ages("Sara") = 30
For Each kvp In ages
Console.WriteLine($"{kvp.Key}: {kvp.Value}")
Next
In this example:
- Ahmed and Sara are keys
- 25 and 30 are values
- kvp.Key accesses the key
- kvp.Value accesses the value
Accessing Dictionary Values
Console.WriteLine(ages("Ahmed"))
Output:
25
Checking Dictionary Keys
The ContainsKey() method checks whether a key exists.
If ages.ContainsKey("Sara") Then
Console.WriteLine("Found")
End If
Choosing Between Arrays & Collections
| Arrays | Collections |
|---|---|
| Fixed size | Dynamic size |
| Faster for simple data | More flexible |
| Less memory overhead | More built-in features |
Real-World Applications
- Student management systems
- Phone books and contact lists
- Inventory systems
- Game scoreboards
- Banking applications
- Shopping cart systems
Best Practices
- Use arrays for fixed-size data
- Use lists for dynamic data
- Use dictionaries for fast key-based lookup
- Choose meaningful variable names
- Validate indexes before accessing elements
Build a phone book using Dictionary(Of String, String).
Try adding:
- Add new contacts
- Search contacts by name
- Delete contacts
- Display all saved entries
Summary
In this lecture, we learned about arrays and collections in Visual Basic. We explored arrays, lists, dictionaries, looping techniques, and data storage methods.
Arrays and collections are essential tools for organizing and processing data efficiently in modern applications.
Exception Handling
Exception handling is a mechanism used to detect and manage runtime errors in a program. Instead of crashing the application, exception handling allows developers to respond to errors gracefully.
Errors can occur for many reasons such as invalid user input, missing files, network failures, or mathematical mistakes. VB.NET provides powerful tools for handling these situations safely.
What is an Exception?
An exception is an unexpected problem that occurs while a program is running. When an exception occurs, normal program execution stops unless the error is handled properly.
Common exceptions include:
- Division by zero
- Invalid file paths
- Incorrect data formats
- Array index out of range
- Null reference errors
Why Exception Handling is Important
- Prevents application crashes
- Improves user experience
- Helps identify bugs
- Protects important data
- Makes programs more reliable
Try-Catch-Finally
VB.NET handles exceptions using the Try, Catch, and Finally blocks.
Try
Dim x = Integer.Parse("abc")
Catch ex As FormatException
Console.WriteLine("Bad format: " & ex.Message)
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
Console.WriteLine("Cleanup done.")
End Try
In this example:
- Try contains risky code
- Catch handles exceptions
- FormatException handles invalid number formats
- Finally executes whether an error occurs or not
Output:
Bad format: Input string was not in a correct format. Cleanup done.
Understanding Try Block
The Try block contains code that may generate exceptions during execution.
Try
Dim result = 10 / 0
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
If an exception occurs inside the Try block, program control immediately moves to the appropriate Catch block.
Multiple Catch Blocks
Programs can use multiple catch blocks to handle different exception types separately.
Try
Dim nums(2) As Integer
Console.WriteLine(nums(5))
Catch ex As IndexOutOfRangeException
Console.WriteLine("Invalid index")
Catch ex As Exception
Console.WriteLine("General error")
End Try
Specific exceptions should always be placed before general exceptions.
The Finally Block
The Finally block always executes regardless of whether an exception occurs.
It is commonly used for cleanup operations.
Try
Console.WriteLine("Program running")
Finally
Console.WriteLine("Resources released")
End Try
Typical uses of Finally include:
- Closing files
- Releasing database connections
- Cleaning temporary resources
- Saving logs
Common Exception Types
| Exception | Description |
|---|---|
| FormatException | Invalid data format |
| DivideByZeroException | Division by zero |
| FileNotFoundException | Missing file |
| IndexOutOfRangeException | Invalid array index |
| NullReferenceException | Using null objects |
Throwing Exceptions
Developers can manually generate exceptions using the Throw keyword.
Dim age As Integer = -5
If age < 0 Then
Throw New Exception("Age cannot be negative")
End If
Throw Custom Exception
Custom exceptions help create more meaningful and application-specific error handling.
Class InsufficientFundsException
Inherits Exception
Sub New(msg As String)
MyBase.New(msg)
End Sub
End Class
If balance < amount Then
Throw New InsufficientFundsException("Not enough money!")
End If
In this example:
- InsufficientFundsException is a custom exception class
- Inherits Exception extends the base Exception class
- Throw generates the custom error
Using Message Property
The Message property provides detailed information about an exception.
Catch ex As Exception
Console.WriteLine(ex.Message)
End Catch
Error Logging
Applications often log exceptions into files for debugging and maintenance.
Catch ex As Exception
File.AppendAllText(
"errors.txt",
ex.Message & vbCrLf
)
End Catch
Nested Exception Handling
Exception handling blocks can also be nested inside each other.
Try
Try
Dim x = 10 / 0
Catch ex As DivideByZeroException
Console.WriteLine("Math error")
End Try
Catch ex As Exception
Console.WriteLine("Outer error")
End Try
Best Practices for Exception Handling
- Handle only expected exceptions
- Use specific exception types when possible
- Avoid empty catch blocks
- Log important errors
- Use Finally for cleanup tasks
- Do not overuse exceptions for normal logic
Real-World Applications
- Banking software
- Web applications
- Database systems
- Game development
- Desktop applications
- Cloud services
Advantages of Exception Handling
- Improves application stability
- Provides better debugging support
- Prevents sudden crashes
- Improves software reliability
- Creates safer applications
Wrap a file-read operation in try-catch handling FileNotFound and IOException.
Try adding:
- Custom error messages
- Error logging to a file
- User input validation
- Finally block cleanup operations
Summary
In this lecture, we learned how exception handling works in VB.NET using Try, Catch, Finally, and Throw statements.
We explored built-in exceptions, custom exceptions, error logging, nested handling, and best practices for building reliable applications.
Exception handling is a critical skill that helps developers create stable and professional software systems.
Classes & Objects
Defining a Class
Class Person
Public Property Name As String
Public Property Age As Integer
Sub New(n As String, a As Integer)
Name = n : Age = a
End Sub
Sub Greet()
Console.WriteLine($"Hi, I'm {Name}")
End Sub
End Class
Dim p As New Person("Ahmed", 25)
p.Greet()Read-Only Properties
Class Circle
Public Property Radius As Double
Public ReadOnly Property Area As Double
Get
Return Math.PI * Radius * Radius
End Get
End Property
End ClassCreate a BankAccount class with Deposit, Withdraw, and Balance.
Inheritance & Polymorphism
Inheritance
Class Animal
Public Overridable Sub Speak()
Console.WriteLine("...")
End Sub
End Class
Class Dog
Inherits Animal
Public Overrides Sub Speak()
Console.WriteLine("Woof!")
End Sub
End ClassAbstract / MustInherit
MustInherit Class Shape
Public MustOverride Function Area() As Double
End Class
Class Square
Inherits Shape
Public Property Side As Double
Public Overrides Function Area() As Double
Return Side * Side
End Function
End ClassCreate Shape, Circle, Rectangle classes using inheritance and polymorphism.
Interfaces & Generics
Interface
Interface IPrintable
Sub Print()
End Interface
Class Document
Implements IPrintable
Public Sub Print() Implements IPrintable.Print
Console.WriteLine("Printing doc...")
End Sub
End ClassGeneric Class
Class Stack(Of T)
Private items As New List(Of T)
Sub Push(x As T) : items.Add(x) : End Sub
Function Pop() As T
Dim x = items(items.Count - 1)
items.RemoveAt(items.Count - 1)
Return x
End Function
End Class
Dim s As New Stack(Of Integer)
s.Push(1) : s.Push(2)
Console.WriteLine(s.Pop()) ' 2Build a generic Queue(Of T) class with Enqueue and Dequeue.
LINQ
Query Syntax
Dim nums = {1, 2, 3, 4, 5, 6}
Dim evens = From n In nums
Where n Mod 2 = 0
Select n
For Each e In evens : Console.WriteLine(e) : NextMethod Syntax
Dim doubled = nums.Where(Function(n) n > 2) _
.Select(Function(n) n * 2) _
.ToList()
Dim total = nums.Sum()
Dim avg = nums.Average()
Dim sorted = nums.OrderByDescending(Function(n) n)Group By
Dim words = {"apple", "ant", "banana", "berry"}
Dim grouped = words.GroupBy(Function(w) w(0))
For Each g In grouped
Console.WriteLine($"{g.Key}: {String.Join(",", g)}")
NextGiven a list of Person objects, use LINQ to find adults grouped by city.
Windows Forms & UI
First Windows Form
Public Class MainForm
Inherits Form
Private btn As New Button() With { _
.Text = "Click Me", _
.Location = New Point(50, 50) _
}
Public Sub New()
Me.Text = "Hello VB"
Me.Size = New Size(300, 200)
AddHandler btn.Click, AddressOf Btn_Click
Me.Controls.Add(btn)
End Sub
Private Sub Btn_Click(sender As Object, e As EventArgs)
MessageBox.Show("Hello!")
End Sub
End ClassCommon Controls
| Control | Purpose |
|---|---|
| TextBox | Single-line text input |
| Label | Static text |
| Button | Clickable button |
| ComboBox | Drop-down list |
| ListBox | List of items |
| DataGridView | Tabular data display |
Build a temperature converter form (Celsius โ Fahrenheit).
Events & Delegates
Custom Events
Class Counter
Public Event ThresholdReached(value As Integer)
Private count As Integer = 0
Sub Increment()
count += 1
If count = 10 Then
RaiseEvent ThresholdReached(count)
End If
End Sub
End Class
Dim c As New Counter()
AddHandler c.ThresholdReached, Sub(v) Console.WriteLine($"Reached {v}!")
For i = 1 To 10 : c.Increment() : NextDelegates
Delegate Function MathOp(a As Integer, b As Integer) As Integer Dim add As MathOp = Function(a, b) a + b Dim mul As MathOp = Function(a, b) a * b Console.WriteLine(add(2, 3)) ' 5 Console.WriteLine(mul(2, 3)) ' 6
Build a Stopwatch class that raises a Tick event every second.
ADO.NET Database
SQL Connection
Imports System.Data.SqlClient
Dim cs As String = "Server=.;Database=Shop;Integrated Security=True"
Using conn As New SqlConnection(cs)
conn.Open()
Dim cmd As New SqlCommand("SELECT * FROM Products", conn)
Using reader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("Name"))
End While
End Using
End UsingInsert / Update
Dim cmd As New SqlCommand(
"INSERT INTO Products (Name, Price) VALUES (@n, @p)", conn)
cmd.Parameters.AddWithValue("@n", "Apple")
cmd.Parameters.AddWithValue("@p", 1.5)
cmd.ExecuteNonQuery()DataAdapter & DataSet
Dim adapter As New SqlDataAdapter("SELECT * FROM Products", conn)
Dim ds As New DataSet()
adapter.Fill(ds, "Products")
dataGridView1.DataSource = ds.Tables("Products")Build a contact manager that stores names and phones in SQL Server.
Async & Threading
Async / Await
Async Function FetchAsync(url As String) As Task(Of String)
Using client As New HttpClient()
Return Await client.GetStringAsync(url)
End Using
End Function
Private Async Sub btnLoad_Click(sender As Object, e As EventArgs)
Dim html = Await FetchAsync("https://example.com")
txtResult.Text = html
End SubThreading
Imports System.Threading
Dim t As New Thread(Sub()
For i = 1 To 5
Console.WriteLine($"Worker: {i}")
Thread.Sleep(500)
Next
End Sub)
t.Start()BackgroundWorker
AddHandler bgWorker.DoWork, Sub(s, e) e.Result = LongTask() AddHandler bgWorker.RunWorkerCompleted, Sub(s, e) lbl.Text = e.Result.ToString() bgWorker.RunWorkerAsync()
Build an async file downloader with progress bar.
Capstone: Inventory Manager Desktop App
Project Overview
Build a full inventory management Windows Forms application using everything you've learned.
Features
- User login screen (with hashed passwords)
- Product CRUD via SQL Server
- Stock-low alerts
- Invoice generation & PDF export
- Sales reports with charts
- Multi-user roles (admin / cashier)
Architecture
InventoryApp/
Forms/ ' Windows Forms .vb files
LoginForm.vb
MainForm.vb
ProductForm.vb
Models/ ' Domain classes
Product.vb
User.vb
Data/ ' ADO.NET data access
ProductRepository.vb
Helpers/ ' PDF, hashing utilities
Program.vb ' Entry pointBonus Challenges
- Add barcode scanner integration
- Export reports to Excel using EPPlus
- Add a dashboard with charts (System.Windows.Forms.DataVisualization)
- Package as MSI installer
Build the full app. Deploy it as an MSI installer. Share GitHub link!