Lesson 13: Mastering If..Then..Else in VB2022

Implementing conditional logic to control program flow in Visual Basic

Key Takeaway

Conditional statements are the backbone of decision-making in programming. Mastering If..Then..Else structures allows you to create applications that respond intelligently to different conditions and user inputs.

Welcome to Lesson 13 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to control program flow using conditional statements. From basic comparisons to complex logical expressions, you'll gain the skills to make your applications respond dynamically to different scenarios.

Learning Objectives

  • Understand VB2022 conditional and logical operators
  • Master If..Then, If..Then..Else, and If..Then..ElseIf structures
  • Implement nested conditional statements
  • Create practical applications with decision-making logic
  • Validate user input using conditional statements
  • Build complex logical expressions
  • Implement error handling with conditionals

13.1 Conditional Operators

VB.NET provides operators for comparing values and making decisions:

Equal To

=

Checks if two values are equal

5 = 5 ' True

Not Equal To

<>

Checks if two values are different

5 <> 3 ' True

Greater Than

>

Checks if left value is larger

10 > 5 ' True

Less Than

<

Checks if left value is smaller

5 < 10 ' True

Greater Than or Equal

>=

Checks if left is larger or equal

8 >= 8 ' True

Less Than or Equal

<=

Checks if left is smaller or equal

5 <= 5 ' True

Best Practice

When comparing strings, be mindful of case sensitivity. Use String.Compare or convert both strings to the same case for case-insensitive comparisons.

13.2 Logical Operators

Combine multiple conditions using logical operators:

AND Operator

Both conditions must be true

(age >= 18) And (hasLicense)

OR Operator

At least one condition must be true

(isStudent) Or (isSenior)

NOT Operator

Reverses the boolean result

Not (isComplete)

XOR Operator

Exactly one condition must be true

(isDay) Xor (isNight)

13.3 Conditional Structures

VB2022 provides several structures for implementing conditional logic:

13.3.1 If..Then Statement

Execute code only when a condition is true:

BasicIf.vb
If temperature > 30 Then
    lblMessage.Text = "It's a hot day!"
    btnCooling.Visible = True
End If

13.3.2 If..Then..Else Statement

Provide alternative execution paths:

IfElse.vb
If score >= 50 Then
    lblResult.Text = "Pass"
    lblResult.BackColor = Color.LightGreen
Else
    lblResult.Text = "Fail"
    lblResult.BackColor = Color.LightPink
End If

13.3.3 If..Then..ElseIf Statement

Handle multiple exclusive conditions:

ElseIf.vb
Dim discount As Double

If purchaseAmount > 200 Then
    discount = 0.2 ' 20% discount
ElseIf purchaseAmount > 100 Then
    discount = 0.1 ' 10% discount
ElseIf purchaseAmount > 50 Then
    discount = 0.05 ' 5% discount
Else
    discount = 0 ' No discount
End If

lblDiscount.Text = (discount * 100).ToString() & "%"

13.3.4 Nested If Statements

Create complex decision trees with nested conditionals:

NestedIf.vb
If userRole = "Admin" Then
    ' Admin-specific features
    btnDelete.Visible = True
    btnEdit.Visible = True
    
    If isSuperAdmin Then
        ' Super admin features
        btnAuditLog.Visible = True
        btnConfig.Visible = True
    End If
    
ElseIf userRole = "Editor" Then
    ' Editor features
    btnEdit.Visible = True
    btnCreate.Visible = True
    
Else
    ' Standard user features
    btnView.Visible = True
End If

Important Note

While nested If statements are powerful, they can become difficult to read when overused. For complex decision trees with many branches, consider using Select Case statements or refactoring your code into separate methods.

13.4 Practical Examples

Let's implement some practical applications using conditional logic:

1 Login System

Validate user credentials with multiple conditions:

LoginSystem.vb
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Dim username As String = txtUsername.Text.Trim()
    Dim password As String = txtPassword.Text
    
    ' Check for empty fields
    If String.IsNullOrEmpty(username) Or String.IsNullOrEmpty(password) Then
        MessageBox.Show("Please enter both username and password", "Input Error")
        Return
    End If
    
    ' Validate credentials
    If username = "admin" And password = "Secure123!" Then
        MessageBox.Show("Admin access granted!", "Login Successful")
        OpenAdminDashboard()
    ElseIf username = "user" And password = "Pass2022" Then
        MessageBox.Show("User access granted!", "Login Successful")
        OpenUserDashboard()
    Else
        MessageBox.Show("Invalid username or password", "Login Failed")
        attempts += 1
        
        If attempts >= 3 Then
            MessageBox.Show("Account locked! Too many failed attempts")
            btnLogin.Enabled = False
        End If
    End If
End Sub

2 Grade Calculator

Convert numerical scores to letter grades:

GradeCalculator.vb
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim score As Integer
    
    ' Validate input
    If Not Integer.TryParse(txtScore.Text, score) Then
        MessageBox.Show("Please enter a valid numeric score")
        Return
    End If
    
    If score < 0 Or score > 100 Then
        MessageBox.Show("Score must be between 0 and 100")
        Return
    End If
    
    ' Determine grade
    Dim grade As String
    
    If score >= 90 Then
        grade = "A"
    ElseIf score >= 80 Then
        grade = "B"
    ElseIf score >= 70 Then
        grade = "C"
    ElseIf score >= 60 Then
        grade = "D"
    Else
        grade = "F"
    End If
    
    lblResult.Text = $"Grade: {grade}"
    
    ' Additional feedback
    If grade = "A" Then
        lblFeedback.Text = "Excellent work!"
        lblFeedback.ForeColor = Color.DarkGreen
    ElseIf grade = "F" Then
        lblFeedback.Text = "Please see your instructor"
        lblFeedback.ForeColor = Color.DarkRed
    Else
        lblFeedback.Text = "Good effort"
        lblFeedback.ForeColor = Color.Blue
    End If
End Sub

3 Temperature Alert

Provide alerts based on temperature ranges:

TemperatureAlert.vb
Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
    Dim temp As Double
    
    ' Validate input
    If Not Double.TryParse(txtTemperature.Text, temp) Then
        MessageBox.Show("Please enter a valid temperature")
        Return
    End If
    
    ' Determine alert level
    Dim alert As String
    Dim color As Color
    
    If temp > 40 Then
        alert = "EXTREME HEAT WARNING! Avoid outdoor activities"
        color = Color.DarkRed
    ElseIf temp > 35 Then
        alert = "Heat Warning: Stay hydrated"
        color = Color.OrangeRed
    ElseIf temp > 30 Then
        alert = "Hot day: Limit sun exposure"
        color = Color.Orange
    ElseIf temp > 20 Then
        alert = "Pleasant weather"
        color = Color.Green
    ElseIf temp > 10 Then
        alert = "Cool: Bring a jacket"
        color = Color.Blue
    ElseIf temp > 0 Then
        alert = "Cold: Dress warmly"
        color = Color.DarkBlue
    Else
        alert = "FREEZING: Avoid prolonged exposure"
        color = Color.Purple
    End If
    
    lblAlert.Text = alert
    lblAlert.ForeColor = color
End Sub

13.4.1 Age Verification System

Check age eligibility for different services:

AgeVerification.vb
Private Sub btnVerify_Click(sender As Object, e As EventArgs) Handles btnVerify.Click
    Dim age As Integer
    
    ' Validate input
    If Not Integer.TryParse(txtAge.Text, age) Or age < 0 Or age > 120 Then
        MessageBox.Show("Please enter a valid age between 0 and 120")
        Return
    End If
    
    ' Determine eligibility
    Dim message As String
    
    If age >= 21 Then
        message = "Full Access: You can purchase all restricted items"
        pnlFullAccess.Visible = True
    ElseIf age >= 18 Then
        message = "Partial Access: You can purchase some restricted items"
        pnlPartialAccess.Visible = True
    Else
        message = "Restricted: No access to age-restricted items"
        pnlRestricted.Visible = True
    End If
    
    ' Additional checks
    If age >= 65 Then
        message &= " (Senior discount available!)"
        lblSeniorDiscount.Visible = True
    End If
    
    lblStatus.Text = message
End Sub

Lesson Summary

In this lesson, we've covered essential concepts about conditional logic in VB2022:

Conditional Operators

=, <>, >, <, >=, <= for value comparisons

Logical Operators

And, Or, Not, Xor for combining conditions

If Structures

If..Then, If..Then..Else, and If..Then..ElseIf

Nested Conditionals

Creating complex decision trees

Practical Applications

Login systems, grading calculators, and alerts

These skills are fundamental for creating responsive applications. In the next lesson, we'll explore Select Case statements as an alternative to complex If structures.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Simple Calculator

Create a calculator that:

  1. Takes two numbers and an operator (+, -, *, /)
  2. Performs the appropriate calculation
  3. Handles division by zero with an error message
  4. Displays the result formatted to two decimal places

Exercise 2: Password Strength Checker

Build an application that:

  1. Analyzes password strength based on:
    • Length (8+ characters)
    • Contains uppercase letters
    • Contains numbers
    • Contains special characters
  2. Provides feedback on password strength (Weak, Medium, Strong)

Exercise 3: Shipping Cost Calculator

Implement a solution that:

  1. Calculates shipping costs based on:
    • Package weight (under 1kg, 1-5kg, 5-10kg, 10kg+)
    • Destination (local, state, national, international)
    • Express shipping option
  2. Displays the calculated shipping cost

Next Lesson

Ready to learn about alternative selection structures? Continue to Lesson 14: Select Case in VB2022.

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