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
Not Equal To
Checks if two values are different
Greater Than
Checks if left value is larger
Less Than
Checks if left value is smaller
Greater Than or Equal
Checks if left is larger or equal
Less Than or Equal
Checks if left is smaller or equal
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
OR Operator
At least one condition must be true
NOT Operator
Reverses the boolean result
XOR Operator
Exactly one condition must be true
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:
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:
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:
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:
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:
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:
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:
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:
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:
- Takes two numbers and an operator (+, -, *, /)
- Performs the appropriate calculation
- Handles division by zero with an error message
- Displays the result formatted to two decimal places
Exercise 2: Password Strength Checker
Build an application that:
- Analyzes password strength based on:
- Length (8+ characters)
- Contains uppercase letters
- Contains numbers
- Contains special characters
- Provides feedback on password strength (Weak, Medium, Strong)
Exercise 3: Shipping Cost Calculator
Implement a solution that:
- Calculates shipping costs based on:
- Package weight (under 1kg, 1-5kg, 5-10kg, 10kg+)
- Destination (local, state, national, international)
- Express shipping option
- Displays the calculated shipping cost
Next Lesson
Ready to learn about alternative selection structures? Continue to Lesson 14: Select Case in VB2022.
Related Resources

Visual Basic 2022 Made Easy
The ultimate beginner-friendly guide for mastering Windows-based application development using Visual Basic in Visual Studio 2022. Whether you're a student, teacher, hobbyist, or self-learner, this book offers a clear, step-by-step approach to help you get started with ease.
What You'll Learn:
- String manipulation techniques
- Text processing and validation
- Regular expressions for advanced matching
- File I/O operations with text
- Practical text-based applications

Mastering Excel VBA 365
Your ultimate step-by-step guide to automating tasks, building macros, and creating powerful applications within Microsoft Excel 365. Whether you're a student, business professional, or aspiring programmer, this comprehensive handbook will help you unlock the full potential of Excel's VBA.
What You'll Learn:
- String functions in Excel VBA
- Text parsing and extraction
- Data cleaning techniques
- Report generation
- Automated text processing