Lesson 5: Working with Controls in VB2022

Mastering TextBox and Label Controls for Effective User Interaction

Key Takeaway

Textbox and Label controls are fundamental building blocks of VB2022 applications. TextBox controls handle user input and output, while Labels provide context and display information. Mastering these controls is essential for creating intuitive and functional interfaces.

Welcome to Lesson 5 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to effectively work with TextBox and Label controls. These essential components allow you to create applications that accept user input, display results, and provide clear user guidance.

Learning Objectives

  • Understand TextBox and Label properties and methods
  • Implement input validation techniques
  • Convert between text and numeric data types
  • Create dynamic user interfaces with controls
  • Design practical applications using TextBox and Label

TextBox Control

The TextBox control serves dual purposes: accepting user input and displaying output. While it primarily handles string data, it can also work with numeric values when properly converted.

Key properties:

  • Text: Gets or sets the text content
  • Multiline: Enables multiple lines of text
  • PasswordChar: Masks input with a specified character
  • ReadOnly: Prevents user editing
  • MaxLength: Limits input length

Label Control

The Label control is primarily used for displaying static text to users. Unlike the TextBox, Labels are read-only and cannot be edited by users at runtime.

Key properties:

  • Text: The displayed content
  • Font: Controls text appearance
  • ForeColor: Text color
  • BackColor: Background color
  • AutoSize: Automatically adjusts size to content

Important Note

Always convert text to numeric values using the Val() function before performing mathematical operations. Without conversion, numbers will be treated as strings and concatenated rather than added.

5.1 Basic Calculator with TextBox

Let's create a simple addition calculator using TextBox controls. This example demonstrates how to accept user input, convert text to numbers, perform calculations, and display results.

1 Implementation Steps

  1. Add two TextBox controls to your form
  2. Add a Button control and change its text to "ADD"
  3. Double-click the button to create the Click event handler

2 Code Example

AdditionCalculator.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Convert text to numbers and add them
    Dim sum As Double = Val(TextBox1.Text) + Val(TextBox2.Text)
    
    ' Display the result in a message box
    MsgBox("The sum is " & sum)
End Sub

Behavior: This program adds the values from both text boxes and displays the result in a message box.

VB 2022 Addition Calculator Interface
Figure 5.1: Addition Calculator Interface
Result message box showing the sum
Figure 5.2: Result Message Box

Understanding Val()

The Val() function converts a string to a numeric value. Without it, the plus operator would concatenate the text values instead of performing arithmetic addition.

5.2 Enhanced Calculator with Labels

Let's improve our calculator by adding Label controls for a better user experience. Labels provide context and display results without interrupting the user with message boxes.

1 Implementation Steps

  1. Add two Label controls to your form
  2. Set the first Label's Text to "Sum ="
  3. Set its Font to Bold and Size to 10
  4. Clear the second Label's Text property
  5. Set its Font to Bold, Size to 10, and BackColor to White

2 Code Example

EnhancedCalculator.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Convert text to numbers and add them
    Dim result As Double = Val(TextBox1.Text) + Val(TextBox2.Text)
    
    ' Display the result in the label
    LblSum.Text = result.ToString()
End Sub

Behavior: When the button is clicked, the sum is displayed in the label instead of a message box.

Enhanced calculator with labels
Figure 5.3: Calculator with Result Label

5.3 Input Validation with TextBox

Validating user input is crucial for creating robust applications. This example demonstrates how to validate input and provide feedback to users.

AgeValidation.vb
Private Sub BtnVerify_Click(sender As Object, e As EventArgs) Handles BtnVerify.Click
    ' Check if input is numeric
    If Not IsNumeric(TxtAge.Text) Then
        LblResult.Text = "Please enter a valid number!"
        LblResult.ForeColor = Color.Red
        Return
    End If
    
    ' Convert to number
    Dim age As Integer = CInt(TxtAge.Text)
    
    ' Validate age range
    If age < 0 Or age > 120 Then
        LblResult.Text = "Please enter a realistic age!"
        LblResult.ForeColor = Color.Red
    ElseIf age >= 18 Then
        LblResult.Text = "Access granted. Welcome!"
        LblResult.ForeColor = Color.Green
    Else
        LblResult.Text = "Access denied. You must be 18 or older."
        LblResult.ForeColor = Color.Red
    End If
End Sub

Output:

This example demonstrates:

  • Using IsNumeric() to validate input
  • Converting text to integer with CInt()
  • Implementing range validation
  • Dynamically changing Label properties (text and color)

5.4 Dynamic Content with Labels

Labels can display dynamic content based on user input or system information. This example creates a personalized greeting.

GreetingGenerator.vb
Private Sub BtnGreet_Click(sender As Object, e As EventArgs) Handles BtnGreet.Click
    ' Get current time
    Dim currentTime As DateTime = DateTime.Now
    Dim hour As Integer = currentTime.Hour
    
    ' Determine time of day
    Dim timeOfDay As String
    If hour < 12 Then
        timeOfDay = "morning"
    ElseIf hour < 18 Then
        timeOfDay = "afternoon"
    Else
        timeOfDay = "evening"
    End If
    
    ' Create personalized greeting
    Dim greeting As String = $"Good {timeOfDay}, {TxtName.Text}!"
    
    ' Display greeting and current time
    LblGreeting.Text = greeting
    LblTime.Text = $"Current time: {currentTime.ToString("hh:mm tt")}"
End Sub

Output:

This example shows:

  • Working with DateTime functions
  • Using string interpolation for dynamic text
  • Displaying multiple pieces of information in labels
  • Creating personalized user experiences

Lesson Summary

In this lesson, we covered essential techniques for working with TextBox and Label controls in VB2022:

TextBox Fundamentals

Essential for user input and can display both text and numeric data

Data Conversion

Always convert TextBox values using Val() or CInt() before mathematical operations

Label Usage

Read-only controls perfect for displaying information to users

Dynamic Properties

Change Label properties (text, color, visibility) at runtime

Input Validation

Crucial when working with TextBox controls to ensure data integrity

These skills form the foundation for creating user-friendly interfaces in VB2022. In the next lesson, we'll explore how to work with ListBox and ComboBox controls.

Exercises

Practice what you've learned with these exercises:

Exercise 1: BMI Calculator

Create a BMI calculator with:

  • Textboxes for height (in cm) and weight (in kg)
  • A "Calculate" button
  • A Label to display the BMI result

Formula: BMI = weight / (height/100)^2

Exercise 2: Login Form

Create a login form with:

  • Textboxes for username and password
  • A "Login" button
  • A Label for validation messages

When the button is clicked, validate that both fields are filled. Display appropriate messages.

Exercise 3: Currency Converter

Create a currency converter that:

  • Converts USD to EUR (use 0.85 as conversion rate)
  • Uses a TextBox for USD input
  • Displays the EUR result in a Label
  • Has a "Convert" button

Next Lesson

Ready to learn about more advanced controls? Continue to Lesson 6: Working with ListBox and ComboBox.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More