Diploma in Information Communication Technology (ICT)
Course ContentEvent handling
Habari, Future Programmer! Let's Master Event Handling
Mambo vipi? I hope you are ready for one of the most exciting topics in Visual Basic. Think about your smartphone. You tap on the M-PESA app icon, and the app opens. You swipe left, and the screen changes. You type your PIN, and numbers appear. Each of those actions—a tap, a swipe, a key press—is an event. The phone's software is constantly listening for these events and knows exactly what to do in response.
This is the heart of modern software! Programs don't just run from top to bottom and then stop. They wait for you, the user, to do something. Today, we're going to learn how to make our Visual Basic applications listen and respond just like that. This is called Event Handling, and it's what makes your programs interactive and useful. Let's begin!
What Exactly is an 'Event'?
In the simplest terms, an event is an action that is recognized by your program. It's a signal that something has happened. This action is usually, but not always, initiated by the user.
Here are some common events you will work with:
- Click: The user presses and releases the mouse button on a control (like a button).
- DoubleClick: The user clicks the mouse button twice in quick succession.
- TextChanged: The user types, deletes, or pastes text into a control like a TextBox.
- Load: The form itself has just been loaded into memory and is about to be displayed.
- KeyPress: The user presses a key on the keyboard.
- MouseEnter: The user moves the mouse pointer over a control.
Kenyan Analogy: Imagine you are at a bus stop in Nairobi. A matatu approaches. You wave your hand (this is the event). The conductor sees your wave and tells the driver to stop (this is the event handler, or the response). The program is the conductor, always watching for a specific signal (the event) to perform a specific action (the response).
The Event Handler: Your Code's Response Team
If an event is the "action," the event handler is the "reaction." It is a special block of code (a Sub procedure) that you write to run automatically whenever a specific event occurs for a specific control.
In Visual Basic, an event handler has a very specific structure. Let's break it down:
Private Sub ControlName_EventName(sender As Object, e As EventArgs) Handles ControlName.EventName
' Your code to handle the event goes here!
End Sub
Let's look at the important parts:
Private Sub ... End Sub: This defines a block of code, a procedure.ControlName_EventName: This is the standard naming convention. For a button namedbtnSubmitand itsClickevent, the name would bebtnSubmit_Click. This makes your code easy to read.Handles ControlName.EventName: This is the magic part! TheHandleskeyword is what links this block of code to the actual event of the control. It tells VB, "Hey, whenever theClickevent happens on the control namedbtnSubmit, run this specific code."
Let's Get Practical: "Habari Dunia!"
Enough theory! Let's build something. We will create a simple application with a button and a label. When we click the button, the label's text will change.
Step 1: Design Your Form
Drag a Button and a Label from the Toolbox onto your form. In the Properties window:
- Select the Button. Change its
(Name)to btnShowMessage and itsTextto "Click Me!". - Select the Label. Change its
(Name)to lblDisplay and itsTextto "Waiting...".
+-------------------------------------------+
| Form1 - O X |
+-------------------------------------------+
| |
| +-----------+ |
| | Click Me! | (btnShowMessage) |
| +-----------+ |
| |
| Waiting... (lblDisplay) |
| |
| |
+-------------------------------------------+
Step 2: Create the Event Handler
This is the easy part. In the form designer, simply double-click on the "Click Me!" button. Visual Basic will automatically open the code window and create the empty event handler for the button's most common event—the Click event!
Step 3: Write the Code
Inside the procedure that VB created, type the one line of code that changes the label's text.
Public Class Form1
Private Sub btnShowMessage_Click(sender As Object, e As EventArgs) Handles btnShowMessage.Click
' This code runs ONLY when the button is clicked.
lblDisplay.Text = "Habari Dunia! Welcome to Event Handling!"
End Sub
End Class
Now, run your program (press F5). Click the button and watch the magic happen! You have successfully handled an event.
Image Suggestion: A vibrant, clean digital illustration of a young Kenyan student sitting at a computer, smiling. The computer screen clearly shows the Visual Basic interface with the simple "Habari Dunia!" form and code. The background is a bright, modern classroom or tech hub setting.
A More Useful Example: A Simple Fee Calculator
Let's create a tool to calculate a simplified transaction fee, like for a mobile money transfer.
The Goal: A user enters an amount in a TextBox. They click a "Calculate" button, and the program displays a 2% transaction fee in a Label.
Controls Needed:
- A TextBox named
txtAmount - A Button named
btnCalculatewith Text "Calculate Fee" - A Label named
lblFeeResultwith Text "Fee will be shown here"
Double-click the "Calculate Fee" button to create its Click event handler. Now, let's write the logic.
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
' Step 1: Declare variables to hold our numbers.
Dim amount As Decimal
Dim fee As Decimal
Dim feeRate As Decimal = 0.02 ' This is 2%
' Step 2: Get the user's input from the TextBox.
' We use Decimal.Parse to convert the text into a number for calculations.
amount = Decimal.Parse(txtAmount.Text)
' Step 3: Perform the calculation.
' Formula: fee = amount * feeRate
fee = amount * feeRate
' Step 4: Display the result in the label.
' We use .ToString("C") to format it as currency (e.g., KSh 20.00).
lblFeeResult.Text = "Transaction Fee: " & fee.ToString("C")
End Sub
This event handler demonstrates a complete process: getting input, processing it, and showing output, all triggered by a single button click!
Visualizing the Event Flow
Sometimes it helps to see the process. Here is how the computer thinks when you click that button.
+-----------------+
| User Clicks |
| btnCalculate |
+-----------------+
|
V
+-----------------+
| OS detects the |
| mouse click |
+-----------------+
|
V
+-----------------------------+
| VB Program receives the |
| 'Click' event for the button|
+-----------------------------+
|
V
+-----------------------------+
| VB looks for a Sub that |
| 'Handles btnCalculate.Click'|
+-----------------------------+
|
V
+-----------------------------+
| Executes the code inside |
| that Sub, line by line |
+-----------------------------+
|
V
+-----------------------------+
| The text of lblFeeResult |
| is updated on the screen |
+-----------------------------+
Summary: Your Key Takeaways
- Programs that respond to user actions are called event-driven.
- An Event is an action, like a click or a key press.
- An Event Handler is the specific block of code (
Sub) that runs in response to an event. - The
Handleskeyword is the crucial link between the event and the event handler. - You can create an event handler easily by double-clicking a control in the designer.
Hongera! You now understand the fundamental concept that makes graphical user interfaces (GUIs) work. Keep practicing. Pole pole ndio mwendo. Every great journey starts with a single step, and you've just taken a huge one!
Pro Tip
Take your own short notes while going through the topics.