Lesson 4 · Writing the Code

Writing the Code

Master event-driven programming in Visual Basic 2026 — write code that responds to user actions, use MsgBox for feedback, perform arithmetic, and let GitHub Copilot accelerate every step.

Key Takeaway: Visual Basic 2026 is an event-driven programming language. Your code does not run top-to-bottom like a script — it waits silently and fires only when the user does something: clicks a button, types in a text box, or loads a form. Understanding this model is the single most important concept in VB.NET development.

4.1 The Concept of Event-Driven Programming

In traditional procedural programs, code runs in a fixed sequence from top to bottom. Visual Basic 2026 works differently — the program starts, displays the form, and then waits. When the user performs an action (called an event), the corresponding block of code (called an event handler) runs in response.

Common events you will use constantly include:

EventTriggered WhenTypical Use
ClickUser clicks a controlButtons, labels, picture boxes
TextChangedText in a TextBox changesLive validation, search filtering
LoadForm opens for the first timeSetting initial values, loading data
KeyPressUser presses a keyFiltering input (numbers only, etc.)
MouseEnterMouse moves over a controlHover effects, tooltips
CheckedChangedCheckBox / RadioButton toggledEnabling/disabling other controls
SelectedIndexChangedListBox / ComboBox selection changesUpdating dependent fields

The Event-Driven Flow

👤User Actione.g. clicks button
Event FiresButton.Click
📋Event HandlerSub btnOK_Click()
🖥️UI UpdatesLabel changes

Event Procedure Structure

Every event handler in Visual Basic 2026 follows this exact structure:

Visual Basic 2026 — Event Structure
Private Sub ControlName_EventName(sender As Object, e As EventArgs) Handles ControlName.EventName
    ' Your code goes here
    ' This block runs ONLY when the event fires
End Sub

The key parts are: sender — the control that triggered the event; e — extra data about the event (e.g. mouse position, key pressed); and Handles — which wires this procedure to a specific control's event.

💡 Quick Way to Create an Event Handler

In the Visual Studio 2026 designer, simply double-click any control to automatically generate its default event handler in the code window. For a Button, this creates a Click handler. For a Form, it creates a Load handler. Visual Studio writes the Private Sub signature for you — you just add the code inside.

Events list associated with Form in VB 2026
Figure 4.1 — The events dropdown in the code window showing all events available for a Form. Click any event name to auto-generate its handler.
Events associated with Button control in VB 2026
Figure 4.2 — Events available for the Button control. The Click event is the most commonly used.

4.2 Writing Your First Code

Let's write our first working VB.NET 2026 program. We'll use MsgBox() — Visual Basic's built-in function for showing a popup message to the user — to verify our code is running correctly.

Example 4.1 — Welcome Message on Form Load

FirstApp.vb — Visual Basic 2026
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MsgBox("My First Visual Basic 2026 App", , "Welcome Message")
    End Sub

End Class

When you press F5 to run this program, the form loads and immediately triggers the Form1_Load event, displaying the message box before the form is even visible.

Try It — Simulation 4.1: Welcome Message
Form1

Click the button below to simulate pressing F5 and running the program:

Example 4.2 — Arithmetic Operations

This example demonstrates basic arithmetic in VB.NET 2026. The & operator joins a string and a number for display:

Arithmetic.vb — Visual Basic 2026
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    MsgBox("2 + 5 = " & (2 + 5))
    MsgBox("10 - 3 = " & (10 - 3))
    MsgBox("4 × 6 = " & (4 * 6))
    MsgBox("20 ÷ 5 = " & (20 / 5))
End Sub
Try It — Simulation 4.2: Arithmetic Operations
Form1 — Arithmetic

Enter two numbers and click an operation button to see MsgBox output:

Number 1: Number 2:

4.3 Practical Examples

Example 4.3 — Button Click Changes a Label

This is the most fundamental pattern in VB.NET: a button click event that modifies another control's properties at runtime.

ButtonClick.vb — Visual Basic 2026
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Label1.Text = "Button was clicked!"
    Label1.ForeColor = Color.Blue
    Label1.Font = New Font("Arial", 12, FontStyle.Bold)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ' Reset the label back to default
    Label1.Text = "(waiting for click)"
    Label1.ForeColor = Color.Gray
    Label1.Font = New Font("Arial", 9, FontStyle.Regular)
End Sub
Try It — Simulation 4.3: Button Click Changes Label
Form1
(waiting for click)

Example 4.4 — Text Input Processing with Validation

This example reads text from a TextBox and uses String.IsNullOrEmpty() to validate input before processing it:

TextInput.vb — Visual Basic 2026
Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles btnGreet.Click
    If String.IsNullOrEmpty(txtName.Text) Then
        MsgBox("Please enter your name!", MsgBoxStyle.Exclamation, "Input Required")
    Else
        MsgBox("Hello, " & txtName.Text & "! Welcome to VB 2026.", _
               MsgBoxStyle.Information, "Greeting")
    End If
End Sub
Try It — Simulation 4.4: Text Input & Validation
Form1 — Greeting App
Your Name:

4.4 GitHub Copilot–Assisted Coding in VB 2026

Visual Studio 2026 ships with deep GitHub Copilot integration that transforms how you write event handlers and code logic. Instead of typing every line from scratch, you describe what you want in a plain-English comment and Copilot generates the code instantly.

How Copilot Works in the Code Window

1

Type a Comment Describing Your Intent

Write a comment in the code window explaining what the event handler should do — e.g. ' When button is clicked, validate name input and show a greeting'. Press Enter after the comment.

2

Copilot Suggests the Code (Ghost Text)

Copilot displays its suggestion in grey italic text (called "ghost text") directly in the editor. The code is not yet written — it's just a preview.

3

Accept with Tab

Press Tab to accept the suggestion and insert it. Press Esc to dismiss. Press Alt + ] to cycle through alternative suggestions if the first one doesn't fit your needs.

4

Ask Copilot Chat for More Complex Code

Open View → GitHub Copilot Chat and ask questions in natural language: "Write a VB.NET button click handler that calculates BMI from height and weight TextBoxes". Copilot writes the full code block which you can insert with one click.

Copilot in Action — Generating an Event Handler

GitHub Copilot — Code Suggestion
You typed: ' When btnCalculate is clicked, multiply TextBox1 and TextBox2 values and show result in Label1'
' When btnCalculate is clicked, multiply TextBox1 and TextBox2 values and show result in Label1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim num1 As Double
    Dim num2 As Double
    If Double.TryParse(TextBox1.Text, num1) AndAlso Double.TryParse(TextBox2.Text, num2) Then
        Label1.Text = "Result: " & (num1 * num2).ToString()
    Else
        MessageBox.Show("Please enter valid numbers.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End If
End Sub  ← Press Tab to accept
🤖 Copilot Chat Prompts for Lesson 4

Try these prompts in the Copilot Chat panel while working through this lesson:

  • "Explain what the Handles keyword does in VB.NET"
  • "Write a Form_Load handler that sets the form title, centers it, and shows a welcome MsgBox"
  • "Add input validation to this TextBox Click handler"
  • "Refactor this code to handle division by zero"

4.5 Building a Simple Calculator

Let's combine everything from this lesson — event handlers, arithmetic, validation, and Copilot-assisted coding — into a complete working calculator application. This is the Exercise 1 from the lesson, solved step by step.

Calculator.vb — Visual Basic 2026
Public Class Form1

    ' Helper function — validates and parses both TextBoxes
    Private Function GetNumbers(ByRef n1 As Double, ByRef n2 As Double) As Boolean
        If Not Double.TryParse(txtNum1.Text, n1) OrElse Not Double.TryParse(txtNum2.Text, n2) Then
            MsgBox("Please enter valid numbers in both fields.", MsgBoxStyle.Exclamation, "Input Error")
            Return False
        End If
        Return True
    End Function

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim n1, n2 As Double
        If GetNumbers(n1, n2) Then
            lblResult.Text = "Result: " & (n1 + n2)
        End If
    End Sub

    Private Sub btnSubtract_Click(sender As Object, e As EventArgs) Handles btnSubtract.Click
        Dim n1, n2 As Double
        If GetNumbers(n1, n2) Then
            lblResult.Text = "Result: " & (n1 - n2)
        End If
    End Sub

    Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
        Dim n1, n2 As Double
        If GetNumbers(n1, n2) Then
            lblResult.Text = "Result: " & (n1 * n2)
        End If
    End Sub

    Private Sub btnDivide_Click(sender As Object, e As EventArgs) Handles btnDivide.Click
        Dim n1, n2 As Double
        If GetNumbers(n1, n2) Then
            If n2 = 0 Then
                MsgBox("Cannot divide by zero!", MsgBoxStyle.Critical, "Math Error")
            Else
                lblResult.Text = "Result: " & (n1 / n2)
            End If
        End If
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        txtNum1.Text = ""
        txtNum2.Text = ""
        lblResult.Text = "Result:"
        txtNum1.Focus()
    End Sub

End Class
Try It — Simulation 4.5: Full Working Calculator
VB 2026 Calculator
Number 1:
Number 2:
Result:

📘 Lesson Summary

  • VB 2026 is event-driven — code runs only when events fire (Click, Load, TextChanged, etc.).
  • Every event handler follows the pattern: Private Sub ControlName_Event(...) Handles ControlName.Event.
  • Double-click any control in the designer to auto-generate its default event handler.
  • MsgBox() displays a popup message — use it for output, warnings, and confirmations.
  • The & operator concatenates strings and numbers for display in messages and labels.
  • Use String.IsNullOrEmpty() and Double.TryParse() to validate user input before processing.
  • Always handle division by zero when writing arithmetic code — check if the denominator is 0 first.
  • GitHub Copilot in Visual Studio 2026 generates event handler code from plain-English comments — type your intent, press Tab to accept.

Exercises

Exercise 4.1 — Temperature Converter

  • Add a TextBox for Celsius input and a Label for output
  • Add a Button — on Click, convert Celsius to Fahrenheit using: F = (C × 9/5) + 32
  • Display the result in the Label as "25°C = 77.0°F"
  • Validate that the input is a valid number using Double.TryParse()
  • Copilot challenge: Type ' Convert Celsius to Fahrenheit and display in lblResult' and see what Copilot suggests

Exercise 4.2 — Personal Information Form

  • Add TextBoxes for First Name, Last Name, and Age
  • Add a Submit Button — validate all fields are non-empty
  • If valid: MsgBox("Hello [First] [Last]. You are [Age] years old.")
  • If invalid: show a warning MsgBox identifying which field is empty
  • Add a Clear Button that resets all fields and moves focus to First Name

Exercise 4.3 — Dynamic Label Controller

  • Add a Label and a TextBox + Button to change the label's text at runtime
  • Add a ComboBox pre-loaded with: Red, Blue, Green, Black — changing selection changes label colour
  • Add a CheckBox — when checked, label text is Bold; when unchecked, Regular
  • Add a TrackBar (1–40) to control the label's Font Size live as it is dragged
  • Copilot challenge: Ask Copilot Chat to "Add a FontStyle.Italic toggle button to this form"

Next: Lesson 5 — Working with Controls

Explore the full range of Windows Forms controls in depth — TextBox, ComboBox, ListBox, CheckBox, and more — with event handling for each.

Continue ❯

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Comprehensive coverage of event-driven coding, arithmetic, MsgBox, and control interaction in Visual Basic — the ideal companion to this lesson.

View on Amazon →
Visual Basic Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 fully-explained VB.NET programs — study real event handlers and arithmetic code in complete working applications.

View on Amazon →