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.
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:
| Event | Triggered When | Typical Use |
|---|---|---|
| Click | User clicks a control | Buttons, labels, picture boxes |
| TextChanged | Text in a TextBox changes | Live validation, search filtering |
| Load | Form opens for the first time | Setting initial values, loading data |
| KeyPress | User presses a key | Filtering input (numbers only, etc.) |
| MouseEnter | Mouse moves over a control | Hover effects, tooltips |
| CheckedChanged | CheckBox / RadioButton toggled | Enabling/disabling other controls |
| SelectedIndexChanged | ListBox / ComboBox selection changes | Updating dependent fields |
The Event-Driven Flow
Event Procedure Structure
Every event handler in Visual Basic 2026 follows this exact 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.
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.
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
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.
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:
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
Enter two numbers and click an operation button to see MsgBox output:
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.
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
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:
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
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
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.
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.
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.
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
' 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
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.
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
📘 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()andDouble.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"
Related Resources
← Lesson 3
Enhancing the UI — Toolbox, controls, Picture Viewer, Login Form.
Lesson 5 →
Working with Controls — in-depth coverage of every major WinForms control.
VB Events Docs
Official Microsoft reference for event handling in Visual Basic .NET.
VB Sample Code
62 practical VB.NET programs demonstrating event-driven coding patterns.
Featured Books
Visual Basic 2022 Made Easy
Comprehensive coverage of event-driven coding, arithmetic, MsgBox, and control interaction in Visual Basic — the ideal companion to this lesson.
View on Amazon →
VB Programming With Code Examples
48 fully-explained VB.NET programs — study real event handlers and arithmetic code in complete working applications.
View on Amazon →