Visual Basic: Full Notes

Visual Basic (VB) is an event-driven programming language and an integrated development environment (IDE) developed by Microsoft. It’s a popular choice for building Windows desktop applications rapidly due to its ease of use and visual design capabilities.

1. Introduction to Visual Basic

1.1 What is Visual Basic?

Visual Basic (VB) is a high-level programming language derived from BASIC (Beginner’s All-purpose Symbolic Instruction Code). It allows for the rapid development of graphical user interface (GUI) applications, access to databases, and web services.

Key Characteristics:

  • Event-Driven: Programs execute code in response to events (e.g., button clicks, key presses).
  • Object-Oriented: Supports concepts like objects, classes, properties, and methods.
  • Visual Development: Features a drag-and-drop interface for designing application forms.
  • Simplified Syntax: Designed to be relatively easy to learn and use.

1.2 Features and Benefits

  • Rapid Application Development (RAD): Quickly build applications using visual tools.
  • Rich UI Controls: A wide array of pre-built controls (buttons, text boxes, labels) to create interactive interfaces.
  • Integration with .NET Framework: Leverages the vast libraries and functionalities of the .NET framework (for VB.NET).
  • Database Connectivity: Easy to connect and interact with various databases (e.g., SQL Server, Access).
  • Debugging Tools: Comprehensive tools to find and fix errors in code.

1.3 Setting up the Development Environment (Visual Studio)

To write and run Visual Basic programs, you typically use Visual Studio.

Steps to Get Started:

  1. Download Visual Studio: Visit the official Microsoft Visual Studio website and download the free “Community” edition.
  2. Install Visual Studio:
    • Run the installer.
    • During installation, select the “.NET desktop development” workload. This includes the necessary components for Visual Basic desktop applications.
    • Follow the prompts to complete the installation.
  3. Launch Visual Studio: Once installed, open Visual Studio from your Start Menu.
  4. Create a New Project:
    • From the Visual Studio start screen, select “Create a new project.”
    • Search for “Windows Forms App (.NET Framework)” or “Windows Forms App” (for .NET Core/.NET 5+). Ensure the language filter is set to “Visual Basic.”
    • Give your project a name (e.g., MyFirstVBApp) and choose a location.
    • Click “Create.”

2. Fundamental Concepts

2.1 Events and Event-Driven Programming

In an event-driven program, the flow of execution is determined by events such as user actions (mouse clicks, keyboard presses), sensor outputs, or messages from other programs/threads.

  • Event: An action or occurrence recognized by a program (e.g., ClickKeyDownLoad).
  • Event Handler: A sub-procedure that contains the code to be executed when a specific event occurs for a particular object.

2.2 Objects, Properties, Methods

  • Object: An instance of a class. In VB, forms and controls (like buttons, text boxes) are objects.
  • Property: An attribute or characteristic of an object (e.g., Text property of a button, BackColor of a form, Width of a label). You can read or set properties.
  • Method: An action that an object can perform (e.g., Click() method of a button, Show() method of a form, Close() method).

2.3 Forms and Controls

  • Form: The window on which your application’s user interface is built. It’s the primary container for other UI elements.
  • Control: A GUI element placed on a form that allows user interaction or displays information (e.g., ButtonTextBoxLabelListBox).

3. Your First Program: “Hello World!”

Let’s create a simple program that displays “Hello, World!” when a button is clicked.

Steps:

  1. Create a New Project:
    • Open Visual Studio.
    • Select “Create a new project.”
    • Search for and select “Windows Forms App (.NET Framework)” (Visual Basic template).
    • Name your project HelloWorldApp and click “Create.”
    • You will see a blank form named Form1.vb in the Designer view.
  2. Design the User Interface (UI):
    • Add a Button:
      • In the Toolbox (usually on the left side, if not visible, go to View > Toolbox), find the “Button” control.
      • Drag and drop a Button onto Form1.
      • Select the Button on the form.
      • In the Properties Window (usually on the right side, if not visible, go to View > Properties Window):
        • Change its Name property to btnSayHello.
        • Change its Text property to Say Hello!.
    • Add a Label:
      • From the Toolbox, find the “Label” control.
      • Drag and drop a Label onto Form1.
      • Select the Label.
      • In the Properties Window:
        • Change its Name property to lblMessage.
        • Change its Text property to (Your message will appear here).
        • (Optional) Change Font size or ForeColor for better visibility.
  3. Write the Code:
    • Double-click the btnSayHello button on your form. This will open the code editor and automatically generate an event handler for the button’s Click event.
    Private Sub btnSayHello_Click(sender As Object, e As EventArgs) Handles btnSayHello.Click
        ' This code will execute when the btnSayHello button is clicked
    End Sub
    
    • Inside this event handler, add the following line of code:
    Private Sub btnSayHello_Click(sender As Object, e As EventArgs) Handles btnSayHello.Click
        lblMessage.Text = "Hello, World!" ' Assign the text "Hello, World!" to the Label's Text property
    End Sub
    
  4. Run the Application:
    • Press F5 or click the Start (green play button) button in the Visual Studio toolbar.
    • Your application window will appear. Click the “Say Hello!” button.
    • The label will change to “Hello, World!”.

Screenshot (Conceptual):

  • Form1: A window with a button labeled “Say Hello!” and a label below it initially showing “(Your message will appear here)”.
  • After clicking the button: The label’s text changes to “Hello, World!”.

4. Data Types

Data types define the type of data a variable can hold (e.g., numbers, text, dates, true/false values).

Table: Common Visual Basic Data Types

Data Type Description Size (Bytes) Range/Values Example Declaration
Boolean True or False values 1 True or False Dim isActive As Boolean
Byte Stores whole numbers from 0 to 255 1 0 to 255 Dim age As Byte
Short Small whole numbers 2 -32,768 to 32,767 Dim count As Short
Integer Standard whole numbers 4 -2,147,483,648 to 2,147,483,647 Dim score As Integer
Long Large whole numbers 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Dim population As Long
Single Single-precision floating-point numbers (decimals) 4 -3.4028235E+38 to -1.401298E-45 (negative); 1.401298E-45 to 3.4028235E+38 (positive) Dim price As Single
Double Double-precision floating-point numbers (decimals) 8 -1.79769313486231570E+308 to -4.94065645841246544E-324 (negative); 4.94065645841246544E-324 to 1.79769313486231570E+308 (positive) Dim pi As Double
Decimal High-precision floating-point numbers (decimals) 16 Very large range, suitable for financial calculations Dim salary As Decimal
Char Single Unicode character 2 Any single character Dim initial As Char
String Sequence of characters (text) Varies 0 to 2 billion Unicode characters Dim name As String
Date Date and Time values 8 January 1, 0001 to December 31, 9999 Dim birthday As Date
Object Can store any type of data 4 or 8 Any value in .NET Framework Dim myVar As Object

Type Conversion (Casting): Sometimes you need to convert a value from one data type to another.

  • Implicit Conversion: VB.NET often handles this automatically for safe conversions (e.g., Integer to Long).
  • Explicit Conversion: You force the conversion using functions like CInt()CStr()CDbl()CBool(), or CType().

Example:

Dim strNumber As String = "123"
Dim intNumber As Integer
Dim dblNumber As Double

' Explicit conversion
intNumber = CInt(strNumber) ' Converts string "123" to integer 123
dblNumber = CDbl("3.14")    ' Converts string "3.14" to double 3.14

5. Variables and Constants

5.1 Variables

Variables are named storage locations that hold data, and their values can change during program execution.

  • Declaring Variables: Use the Dim keyword.
    • Syntax: Dim VariableName As DataType

    Examples:

    Dim userName As String
    Dim userAge As Integer
    Dim isManager As Boolean = False ' Declaration and initialization
    Dim temperature As Double = 25.5
    
  • Assigning Values: Use the assignment operator (=).Example:
    userName = "Alice"
    userAge = 30
    
  • Scope of Variables:
    • Local Variable: Declared inside a procedure (Sub or Function). Accessible only within that procedure.
    • Module/Form-Level Variable: Declared outside any procedure but within a Class or Module. Accessible to all procedures within that class/module.
    • Global Variable (less common in modern VB.NET): Declared as Public Shared in a module, accessible throughout the entire application.

    Example (Scope):

    ' Form-level variable
    Private totalClicks As Integer = 0
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Local variable
        Dim message As String = "Welcome!"
        MessageBox.Show(message)
    End Sub
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        totalClicks += 1 ' Accessing form-level variable
        MessageBox.Show("Button clicked " & totalClicks.ToString() & " times.")
        ' message variable is NOT accessible here
    End Sub
    

5.2 Constants

Constants are named storage locations whose values remain fixed throughout the program’s execution.

  • Declaring Constants: Use the Const keyword.
    • Syntax: Const ConstantName As DataType = Value

    Example:

    Const PI As Double = 3.14159
    Const MAX_USERS As Integer = 100
    Const COMPANY_NAME As String = "Tech Solutions Inc."
    
    Private Sub CalculateArea(radius As Double)
        Dim area As Double = PI * radius * radius
        MessageBox.Show("Area: " & area.ToString())
    End Sub
    

6. Operators

Operators are symbols that tell the compiler to perform specific mathematical, relational, or logical operations.

6.1 Arithmetic Operators

Used for mathematical calculations.

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 2 12
/ Division (Float) 7 / 2 3.5
\ Integer Division 7 \ 2 3
Mod Modulus (Remainder) 7 Mod 2 1
^ Exponentiation 2 ^ 3 8

Example:

Dim a As Integer = 10
Dim b As Integer = 3
Dim result As Integer

result = a + b ' 13
result = a - b ' 7
result = a * b ' 30
result = a \ b ' 3 (integer division)
result = a Mod b ' 1 (remainder)

Dim powerResult As Double = 2 ^ 4 ' 16.0

6.2 Comparison Operators

Used to compare two values, returning a Boolean (True or False).

Operator Description Example Result
= Equal to a = b False
<> Not equal to a <> b True
< Less than a < b False
> Greater than a > b True
<= Less than or equal to a <= b False
>= Greater than or equal to a >= b True

Example:

Dim x As Integer = 5
Dim y As Integer = 10

Console.WriteLine(x = y)  ' False
Console.WriteLine(x <> y) ' True
Console.WriteLine(x < y)  ' True
Console.WriteLine(x >= y) ' False

6.3 Logical Operators

Used to combine or modify Boolean expressions.

Operator Description Example
And Returns True if both expressions are True (x > 0 And y < 10)
Or Returns True if either expression is True (x > 0 Or y < 10)
Not Reverses the logical state of an expression Not (x > 0)
Xor Returns True if one expression is True and the other is False (isRaining Xor isSunny)
AndAlso Short-circuiting And (more efficient) (IsAdmin AndAlso CheckPassword())
OrElse Short-circuiting Or (more efficient) (IsLoggedIn OrElse ShowLoginScreen())

Example:

Dim age As Integer = 25
Dim hasLicense As Boolean = True

If age >= 18 And hasLicense Then
    Console.WriteLine("Eligible to drive.")
Else
    Console.WriteLine("Not eligible to drive.")
End If

6.4 Concatenation Operator

Used to join strings together.

Operator Description Example Result
& Concatenates strings "Hello" & " World" "Hello World"
+ Can also concatenate strings, but & is preferred for clarity and type safety. "Hello" + " World" "Hello World"

Example:

Dim firstName As String = "John"
Dim lastName As String = "Doe"
Dim fullName As String = firstName & " " & lastName ' "John Doe"

Console.WriteLine("Welcome, " & fullName & "!")

7. Control Flow Statements

Control flow statements determine the order in which instructions are executed.

7.1 Conditional Statements

Allow different code blocks to run based on whether a condition is True or False.

  • If...Then...ElseIf...Else...End If Executes a block of code conditionally.Syntax:
    If condition1 Then
        ' Code to execute if condition1 is True
    ElseIf condition2 Then
        ' Code to execute if condition1 is False and condition2 is True
    Else
        ' Code to execute if all conditions are False
    End If
    

    Example:

    Dim score As Integer = 85
    
    If score >= 90 Then
        Console.WriteLine("Grade: A")
    ElseIf score >= 80 Then
        Console.WriteLine("Grade: B")
    ElseIf score >= 70 Then
        Console.WriteLine("Grade: C")
    Else
        Console.WriteLine("Grade: F")
    End If
    
  • Select Case Provides a more readable way to handle multiple conditional branches based on a single expression.Syntax:
    Select Case expression
        Case value1
            ' Code for value1
        Case value2, value3
            ' Code for value2 or value3
        Case Is > 100
            ' Code if expression is greater than 100
        Case Else
            ' Code if none of the above match
    End Select
    

    Example:

    Dim dayOfWeek As Integer = 3 ' 1=Sunday, 2=Monday...
    
    Select Case dayOfWeek
        Case 1
            Console.WriteLine("It's Sunday!")
        Case 2 To 6 ' Range of values
            Console.WriteLine("It's a weekday.")
        Case 7
            Console.WriteLine("It's Saturday!")
        Case Else
            Console.WriteLine("Invalid day.")
    End Select
    

7.2 Looping Statements

Allow a block of code to be executed repeatedly.

  • For...Next Repeats a block of code a specified number of times.Syntax:
    For counter = start To end [Step increment]
        ' Code to execute
    Next [counter]
    

    Example:

    ' Loop from 1 to 5
    For i As Integer = 1 To 5
        Console.WriteLine("Count: " & i.ToString())
    Next
    
    ' Loop from 10 down to 0, stepping by 2
    For j As Integer = 10 To 0 Step -2
        Console.WriteLine("Countdown: " & j.ToString())
    Next
    
  • For Each...Next Iterates through each item in a collection (e.g., an array, a list).Syntax:
    For Each element In collection
        ' Code to execute for each element
    Next [element]
    

    Example:

    Dim names() As String = {"Alice", "Bob", "Charlie"}
    
    For Each name As String In names
        Console.WriteLine("Name: " & name)
    Next
    
  • Do While...Loop Repeats a block of code as long as a condition is True. The condition is checked before the loop’s first iteration.Syntax:
    Do While condition
        ' Code to execute
    Loop
    

    Example:

    Dim count As Integer = 0
    Do While count < 5
        Console.WriteLine("Do While count: " & count.ToString())
        count += 1
    Loop
    
  • Loop While (variant of Do...Loop) Executes the loop body at least once, then checks the condition.Syntax:
    Do
        ' Code to execute
    Loop While condition
    

    Example:

    Dim x As Integer = 0
    Do
        Console.WriteLine("Loop While x: " & x.ToString())
        x += 1
    Loop While x < 3 ' Will execute 3 times
    
  • Do Until...Loop Repeats a block of code until a condition becomes True. The condition is checked before the loop’s first iteration.Syntax:
    Do Until condition
        ' Code to execute
    Loop
    

    Example:

    Dim timer As Integer = 5
    Do Until timer = 0
        Console.WriteLine("Timer: " & timer.ToString())
        timer -= 1
    Loop
    Console.WriteLine("Blast off!")
    
  • Loop Until (variant of Do...Loop) Executes the loop body at least once, then checks the condition.Syntax:
    Do
        ' Code to execute
    Loop Until condition
    

    Example:

    Dim passwordInput As String
    Do
        passwordInput = InputBox("Enter password:")
    Loop Until passwordInput = "secret"
    MessageBox.Show("Password correct!")
    

8. Procedures and Functions

Procedures and functions are blocks of code designed to perform a specific task. They promote code reusability and modularity.

8.1 Sub Procedures

  • Sub procedure performs a task but does not return a value.
  • Declared using the Sub keyword.Syntax:
    [AccessModifier] Sub ProcedureName([ParameterList])
        ' Code to execute
    End Sub
    

    Example:

    ' Sub with no parameters
    Private Sub DisplayWelcomeMessage()
        MessageBox.Show("Welcome to the application!")
    End Sub
    
    ' Sub with parameters
    Private Sub GreetUser(ByVal name As String)
        MessageBox.Show("Hello, " & name & "!")
    End Sub
    
    ' How to call them (e.g., from a button click event)
    Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles btnGreet.Click
        DisplayWelcomeMessage()
        GreetUser("Alice")
        GreetUser(TextBox1.Text) ' Greet based on text box input
    End Sub
    

8.2 Function Procedures

  • Function procedure performs a task and returns a value.
  • Declared using the Function keyword, and you must specify the return data type.Syntax:
    [AccessModifier] Function FunctionName([ParameterList]) As ReturnDataType
        ' Code to execute
        Return valueToReturn
    End Function
    

    Example:

    ' Function to add two numbers
    Private Function AddNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
        Dim sum As Integer = num1 + num2
        Return sum
    End Function
    
    ' Function to check if a number is even
    Private Function IsEven(ByVal number As Integer) As Boolean
        Return (number Mod 2 = 0)
    End Function
    
    ' How to call them and use their return values
    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
        Dim result As Integer
        result = AddNumbers(10, 5) ' Call the function and store its return value
        MessageBox.Show("Sum: " & result.ToString()) ' Sum: 15
    
        If IsEven(result) Then
            MessageBox.Show("The sum is an even number.")
        Else
            MessageBox.Show("The sum is an odd number.")
        End If
    End Sub
    

8.3 Parameters (ByVal, ByRef)

Parameters allow you to pass values into procedures and functions.

  • ByVal (By Value – default): A copy of the argument’s value is passed. Changes to the parameter inside the procedure do not affect the original variable outside the procedure.
  • ByRef (By Reference): A reference to the argument’s memory location is passed. Changes to the parameter inside the procedure do affect the original variable outside the procedure.Example:
    Private Sub ModifyByVal(ByVal num As Integer)
        num = num + 10 ' This change only affects the 'num' parameter within this sub
    End Sub
    
    Private Sub ModifyByRef(ByRef num As Integer)
        num = num + 10 ' This change affects the original variable passed to this sub
    End Sub
    
    Private Sub btnParamTest_Click(sender As Object, e As EventArgs) Handles btnParamTest.Click
        Dim myValue As Integer = 5
    
        ModifyByVal(myValue)
        MessageBox.Show("After ByVal: " & myValue.ToString()) ' Output: 5 (original value unchanged)
    
        ModifyByRef(myValue)
        MessageBox.Show("After ByRef: " & myValue.ToString()) ' Output: 15 (original value changed)
    End Sub
    

9. Arrays

An array is a collection of elements of the same data type, stored in contiguous memory locations.

9.1 Declaring Arrays

  • Fixed-size array:
    • Syntax: Dim ArrayName(upperBound) As DataType (upperBound is the largest index)
    • Example: Dim numbers(4) As Integer (creates an array with 5 elements, indices 0 to 4)
  • Dynamic array (declare without size):
    • Syntax: Dim ArrayName() As DataType
    • You use ReDim later to set or change its size.

Examples:

' Fixed-size array of 5 integers (indices 0 to 4)
Dim scores(4) As Integer

' Fixed-size array of 3 strings, initialized
Dim daysOfWeek() As String = {"Mon", "Tue", "Wed"}

' Dynamic array and then sizing it
Dim studentNames() As String
ReDim studentNames(9) ' Now it can hold 10 names (indices 0 to 9)

9.2 Accessing Elements

Array elements are accessed using their index, starting from 0.

Examples:

Dim colors() As String = {"Red", "Green", "Blue"}

' Accessing elements
Console.WriteLine(colors(0)) ' Output: Red
Console.WriteLine(colors(1)) ' Output: Green

' Assigning a new value
colors(2) = "Yellow"
Console.WriteLine(colors(2)) ' Output: Yellow

' Looping through an array
For Each color As String In colors
    Console.WriteLine("Color: " & color)
Next

' Using a For loop with index
For i As Integer = 0 To colors.Length - 1
    Console.WriteLine("Color at index " & i.ToString() & ": " & colors(i))
Next

9.3 Multidimensional Arrays

Arrays can have multiple dimensions (e.g., rows and columns).

Example (2D Array – Matrix):

' Declare a 2x3 array (2 rows, 3 columns)
Dim matrix(1, 2) As Integer ' (RowUpperIndex, ColumnUpperIndex)

' Initialize elements
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(0, 2) = 3
matrix(1, 0) = 4
matrix(1, 1) = 5
matrix(1, 2) = 6

' Accessing an element
Console.WriteLine(matrix(0, 1)) ' Output: 2

' Loop through a 2D array
For row As Integer = 0 To matrix.GetUpperBound(0) ' GetUpperBound(0) is max index of first dimension
    For col As Integer = 0 To matrix.GetUpperBound(1) ' GetUpperBound(1) is max index of second dimension
        Console.Write(matrix(row, col).ToString() & " ")
    Next
    Console.WriteLine() ' New line after each row
Next
' Output:
' 1 2 3
' 4 5 6

9.4 Dynamic Arrays (ReDim)

You can change the size of a dynamic array at runtime using ReDim.

  • ReDim: Changes the size, loses existing data.
  • ReDim Preserve: Changes the size, preserves existing data. Can only change the upper bound of the last dimension.

Example:

Dim employeeList() As String ' Declare a dynamic array

ReDim employeeList(2) ' Size it for 3 elements (0, 1, 2)
employeeList(0) = "John"
employeeList(1) = "Jane"
employeeList(2) = "Mike"

Console.WriteLine("Original size: " & employeeList.Length) ' 3

' Resize the array, losing data
ReDim employeeList(4) ' Now 5 elements, data from previous employeeList is lost
Console.WriteLine("New size (data lost): " & employeeList.Length) ' 5
' Console.WriteLine(employeeList(0)) ' Will be Nothing or empty string

' Resize the array, preserving data
ReDim Preserve employeeList(5) ' Now 6 elements, original data (if any was there) is kept
employeeList(3) = "Sarah"
employeeList(4) = "David"
employeeList(5) = "Emily"

Console.WriteLine("New size (data preserved): " & employeeList.Length) ' 6
Console.WriteLine(employeeList(5)) ' Output: Emily

10. User Interface (UI) Controls (Common Examples)

Visual Basic offers a rich set of controls for building interactive GUIs. Here are some fundamental ones:

Table: Common UI Controls and Properties

Control Name Description Key Properties Common Events
Button Triggers an action when clicked TextNameEnabledVisible Click
Label Displays static text TextNameAutoSizeFont (Few, mostly for visual updates)
TextBox Allows user to input or display single/multi-line text TextNameBackColorMultilineReadOnlyPasswordChar TextChangedKeyDownKeyUp
ListBox Displays a list of items, allowing single/multi-selection Items (collection), NameSelectionModeSelectedItemSelectedIndex SelectedIndexChanged
ComboBox Drop-down list with optional text input ItemsNameSelectedIndexTextDropDownStyle SelectedIndexChangedTextChanged
CheckBox Two-state option (checked/unchecked) TextNameChecked CheckedChanged
RadioButton Allows selection of one from a group TextNameChecked CheckedChanged
Panel Container for grouping controls NameBackColorBorderStyle (Acts as a container)
GroupBox Similar to Panel, with a title TextName (Acts as a container)
PictureBox Displays images ImageNameSizeMode Click
DateTimePicker Allows selection of a date and/or time ValueFormatShowUpDown ValueChanged

Adding and Customizing Controls (General Steps):

  1. Drag and Drop: From the Toolbox, drag the desired control onto your Form.
  2. Position and Size: Use the mouse to move and resize the control.
  3. Properties Window: Select the control, then use the Properties window to change its attributes (e.g., TextNameFontColor).
    • Name property: Crucial for referring to the control in code (e.g., btnSubmittxtInputlblResult).
    • Text property: Sets the displayed text for buttons, labels, and initial content for text boxes.
  4. Event Handlers: Double-click the control to create its default event handler (e.g., Click for a Button, TextChanged for a TextBox).

11. Handling User Input

Getting input from users and displaying output are essential for interactive applications.

  • TextBox for Input:
    • Place a TextBox control on your form.
    • Access its Text property to read the user’s input.
    • Example: Dim userInput As String = TextBox1.Text
  • MessageBox.Show() for Output/Messages:
    • Displays a standard message box.
    • Syntax: MessageBox.Show("Message Text", "Title", MessageBoxButtons.OK, MessageBoxIcon.Information)

    Example:

    Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
        Dim enteredName As String = txtName.Text ' txtName is the Name of a TextBox control
    
        If String.IsNullOrEmpty(enteredName) Then
            MessageBox.Show("Please enter your name.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Else
            MessageBox.Show("Hello, " & enteredName & "!", "Greeting", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    
  • InputBox() for Simple Input (legacy, but sometimes used):
    • A simple function to get string input from the user via a small dialog.

    Example:

    Private Sub btnInput_Click(sender As Object, e As EventArgs) Handles btnInput.Click
        Dim ageInput As String
        ageInput = InputBox("Please enter your age:", "Age Input", "18") ' Default value "18"
    
        If Not String.IsNullOrEmpty(ageInput) Then
            Try
                Dim age As Integer = CInt(ageInput)
                MessageBox.Show("You entered age: " & age.ToString())
            Catch ex As InvalidCastException
                MessageBox.Show("Invalid age entered. Please enter a number.")
            End Try
        End If
    End Sub
    

12. Error Handling (Try...Catch...Finally)

Robust applications anticipate and handle errors (exceptions) gracefully to prevent crashes.

  • Try...Catch...Finally...End Try block:
    • Try: Contains the code that might cause an error.
    • Catch: Contains the code to execute if an error occurs in the Try block. You can catch specific types of exceptions.
    • Finally: (Optional) Contains code that always executes, regardless of whether an error occurred or not (e.g., for cleanup).
    • End Try: Marks the end of the block.

Syntax:

Try
    ' Code that might generate an exception
Catch ex As ExceptionType ' Optional: Catch a specific type of exception
    ' Code to handle the exception
    ' ex.Message contains the error description
    ' ex.StackTrace contains where the error occurred
Finally
    ' Optional: Code that always runs (e.g., closing files, database connections)
End Try

Example: Let’s modify the InputBox example to use Try...Catch for safer conversion.

Private Sub btnDivide_Click(sender As Object, e As EventArgs) Handles btnDivide.Click
    Dim num1Str As String = txtNum1.Text
    Dim num2Str As String = txtNum2.Text
    Dim result As Double

    Try
        Dim num1 As Double = CDbl(num1Str)
        Dim num2 As Double = CDbl(num2Str)

        If num2 = 0 Then
            ' Explicitly throw an exception if dividing by zero
            Throw New DivideByZeroException("Cannot divide by zero!")
        End If

        result = num1 / num2
        lblResult.Text = "Result: " & result.ToString()

    Catch ex As FormatException ' Catches errors if text is not a valid number
        MessageBox.Show("Invalid input. Please enter valid numbers.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        lblResult.Text = "Error: Invalid number."

    Catch ex As DivideByZeroException ' Catches our custom divide by zero error
        MessageBox.Show(ex.Message, "Calculation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        lblResult.Text = "Error: " & ex.Message

    Catch ex As Exception ' Catches any other unexpected errors
        MessageBox.Show("An unexpected error occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        lblResult.Text = "Error: " & ex.Message
    Finally
        ' This block will always execute
        ' For example, if you had opened a file, you'd close it here.
        ' Console.WriteLine("Calculation attempt finished.")
    End Try
End Sub

13. Object-Oriented Programming (OOP) Concepts (Briefly)

Visual Basic .NET is an object-oriented language. Understanding basic OOP concepts is crucial for building larger, more maintainable applications.

  • Class: A blueprint or template for creating objects. It defines the properties (data) and methods (behaviors) that objects of that class will have.
  • Object: An instance of a class. When you create a button or a form, you are creating an object from its respective class.
  • Properties: Attributes of an object (e.g., TextColorSize).
  • Methods: Actions an object can perform (e.g., Click()Show()Close()).
  • Encapsulation: Bundling data (properties) and methods that operate on the data within a single unit (class), and restricting direct access to some of the object’s components. Achieved using access modifiers (PublicPrivateProtected).
  • Inheritance: Allows a new class (derived class or subclass) to inherit properties and methods from an existing class (base class or superclass), promoting code reuse.
  • Polymorphism: The ability of objects of different classes to respond to the same message (method call) in different ways.

Example (A Simple Class):

' Define a Class
Public Class Car
    ' Properties (data)
    Public Property Make As String
    Public Property Model As String
    Public Property Year As Integer
    Private currentSpeed As Integer ' Encapsulated, accessed via method

    ' Constructor (called when a new object is created)
    Public Sub New(ByVal make As String, ByVal model As String, ByVal year As Integer)
        Me.Make = make
        Me.Model = model
        Me.Year = year
        Me.currentSpeed = 0
    End Sub

    ' Methods (behaviors)
    Public Sub Accelerate(ByVal amount As Integer)
        currentSpeed += amount
        If currentSpeed > 200 Then currentSpeed = 200 ' Max speed
        Console.WriteLine($"{Make} {Model} accelerating. Current speed: {currentSpeed} km/h")
    End Sub

    Public Sub Brake(ByVal amount As Integer)
        currentSpeed -= amount
        If currentSpeed < 0 Then currentSpeed = 0 ' Min speed
        Console.WriteLine($"{Make} {Model} braking. Current speed: {currentSpeed} km/h")
    End Sub

    Public Function GetCurrentSpeed() As Integer
        Return currentSpeed
    End Function
End Class

' How to use the Class and create Objects
Private Sub btnCreateCar_Click(sender As Object, e As EventArgs) Handles btnCreateCar.Click
    ' Create an object (instance) of the Car class
    Dim myCar As New Car("Toyota", "Camry", 2020)

    ' Access properties
    Console.WriteLine("My car is a " & myCar.Year.ToString() & " " & myCar.Make & " " & myCar.Model)

    ' Call methods
    myCar.Accelerate(50)
    myCar.Accelerate(30)
    myCar.Brake(20)

    Console.WriteLine("Final speed: " & myCar.GetCurrentSpeed().ToString() & " km/h")

    Dim anotherCar As New Car("Honda", "Civic", 2022)
    anotherCar.Accelerate(60)
End Sub

14. Example Program: Simple Calculator

Let’s build a basic calculator with addition, subtraction, multiplication, and division.

Steps:

  1. Create a New Project: “Windows Forms App (.NET Framework)” (Visual Basic). Name it SimpleCalculator.
  2. Design the UI (Form1.vb):
    • TextBox for Number 1:
      • Name: txtNum1
      • Text: (empty)
    • TextBox for Number 2:
      • Name: txtNum2
      • Text: (empty)
    • Button for Addition:
      • Name: btnAdd
      • Text: +
    • Button for Subtraction:
      • Name: btnSubtract
      • Text: -
    • Button for Multiplication:
      • Name: btnMultiply
      • Text: *
    • Button for Division:
      • Name: btnDivide
      • Text: /
    • Label for Result:
      • Name: lblResult
      • Text: Result: (or 0)
      • (Optional) Set Font size larger for visibility.
    • Labels for text prompts: Add two Label controls next to txtNum1 and txtNum2 with Text properties like “Number 1:” and “Number 2:”.

    Layout (Conceptual):

    Number 1: [ txtNum1 ]
    Number 2: [ txtNum2 ]
    
    [ + ] [ - ] [ * ] [ / ]
    
    Result: [ lblResult ]
    
  3. Write the Code (Form1.vb):We’ll create a shared function to perform the calculation and handle errors, then call it from each button’s click event.
    Public Class Form1
    
        ' This function will handle the actual calculation and error checking
        Private Function Calculate(ByVal operation As Char) As String
            Dim num1 As Double
            Dim num2 As Double
            Dim result As Double
    
            Try
                ' Attempt to convert text box inputs to numbers
                num1 = CDbl(txtNum1.Text)
                num2 = CDbl(txtNum2.Text)
    
                Select Case operation
                    Case "+"
                        result = num1 + num2
                    Case "-"
                        result = num1 - num2
                    Case "*"
                        result = num1 * num2
                    Case "/"
                        If num2 = 0 Then
                            ' Throw a specific exception for division by zero
                            Throw New DivideByZeroException("Cannot divide by zero!")
                        End If
                        result = num1 / num2
                    Case Else
                        Return "Error: Invalid operation."
                End Select
    
                Return "Result: " & result.ToString()
    
            Catch ex As FormatException ' Catches errors if input is not a valid number
                Return "Error: Please enter valid numbers."
            Catch ex As DivideByZeroException ' Catches our custom divide by zero error
                Return "Error: " & ex.Message
            Catch ex As Exception ' Catches any other unexpected errors
                Return "An unexpected error occurred: " & ex.Message
            End Try
        End Function
    
        ' Event handler for Addition button
        Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
            lblResult.Text = Calculate("+")
        End Sub
    
        ' Event handler for Subtraction button
        Private Sub btnSubtract_Click(sender As Object, e As EventArgs) Handles btnSubtract.Click
            lblResult.Text = Calculate("-")
        End Sub
    
        ' Event handler for Multiplication button
        Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
            lblResult.Text = Calculate("*")
        End Sub
    
        ' Event handler for Division button
        Private Sub btnDivide_Click(sender As Object, e As EventArgs) Handles btnDivide.Click
            lblResult.Text = Calculate("/")
        End Sub
    
    End Class
    
  4. Run the Application:
    • Press F5.
    • Enter numbers in txtNum1 and txtNum2.
    • Click the operation buttons (+-*/).
    • Observe the lblResult update with the calculation or an error message.
    • Try dividing by zero or entering non-numeric text to test error handling.

15. Conclusion

Visual Basic remains a powerful and user-friendly language for developing Windows desktop applications, especially for those who appreciate visual design and rapid development. Its integration with the .NET Framework provides access to extensive libraries and functionalities, making it suitable for a wide range of applications from simple utilities to complex business solutions. Mastering the concepts outlined in these notes will provide a strong foundation for building robust and interactive VB applications.