Lesson 13 · If..Then..Else

If..Then..Else

Master conditional logic in Visual Basic 2026 — If..Then, If..Then..Else, ElseIf chains, nested conditions, logical operators (And, Or, Not, AndAlso, OrElse), the inline If() ternary operator, and .NET 10 pattern-matching improvements. Build smart applications that make decisions.

Key Takeaway: The If..Then..Else structure is the fundamental tool for decision-making in VB 2026. Use simple If..Then for one-way decisions, If..Then..Else for two-way, and If..Then..ElseIf..Else for multi-way decisions. Always use AndAlso and OrElse (short-circuit operators) instead of And/Or — they are faster and prevent null-reference errors. Avoid deep nesting; use ElseIf chains or early Return to keep code flat and readable.

13.1 Comparison and Logical Operators

Conditions in If statements use comparison operators to evaluate relationships between values, and logical operators to combine multiple conditions.

Comparison Operators

=Equal tox = 5
<>Not equal tox <> 0
>Greater thanage > 18
<Less thanscore < 50
>=Greater than or equalmark >= 75
<=Less than or equaltemp <= 0
IsObject reference equalityobj Is Nothing
IsNotObject reference inequalityobj IsNot Nothing
LikePattern matching (wildcard)s Like "A*"

Logical Operators

AndAlsoShort-circuit AND (recommended)a > 0 AndAlso b > 0
OrElseShort-circuit OR (recommended)a = 0 OrElse b = 0
AndBitwise AND (evaluates both)a And b
OrBitwise OR (evaluates both)a Or b
NotLogical negationNot isValid
XorExclusive ORa Xor b
AndAlso vs And — Always use AndAlso!

And evaluates both sides even if the left side is False. AndAlso short-circuits — if the left side is False, it skips the right side entirely. This prevents crashes: If obj IsNot Nothing AndAlso obj.Value > 0 is safe; If obj IsNot Nothing And obj.Value > 0 will crash with a NullReferenceException if obj is Nothing. The same applies to OrElse vs Or.


13.2 If..Then (One-Way Decision)

The simplest form: execute a block only when a condition is True. Nothing happens when the condition is False.

IfThen.vb — Visual Basic 2026
' Single-line If..Then (condition and action on one line)
If score >= 50 Then lblResult.Text = "Pass"

' Block If..Then (multiple statements, requires End If)
If score >= 50 Then
    lblResult.Text = "Pass"
    lblResult.BackColor = Color.LightGreen
    btnNext.Enabled = True
End If

' Checking Nothing (null) before using an object
If lstStudents.SelectedItem IsNot Nothing Then
    lblSelected.Text = lstStudents.SelectedItem.ToString()
End If

' Validating user input before processing
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    If String.IsNullOrWhiteSpace(txtName.Text) Then
        lblError.Text = "Name is required."
        txtName.Focus()
        Return                ' early exit -- nothing else runs
    End If
    ' ... rest of processing
End Sub

13.3 If..Then..Else (Two-Way Decision)

Executes one block when the condition is True, and a different block when it is False. Exactly one branch always runs.

START condition True/False? True Then block False Else block END IF
IfElse.vb
Dim score As Integer
Integer.TryParse(txtScore.Text, score)

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

' Login check example
If txtUser.Text = "admin" AndAlso
   txtPass.Text = "secret123" Then
    lblStatus.Text = "Welcome, Admin!"
    pnlAdmin.Visible = True
Else
    lblStatus.Text = "Invalid credentials."
    txtPass.Clear()
    txtPass.Focus()
End If

13.4 If..Then..ElseIf..Else (Multi-Way Decision)

When there are more than two possible outcomes, chain ElseIf clauses. VB 2026 evaluates each condition top-to-bottom and executes the first matching branch only. The final Else is a catch-all for anything that didn't match.

ElseIf.vb — Visual Basic 2026
' Grade classification using ElseIf chain
Dim mark As Integer
If Not Integer.TryParse(txtMark.Text, mark) Then
    lblGrade.Text = "Invalid input"
    Return
End If

Dim grade As String
If mark >= 90 Then
    grade = "A+"
ElseIf mark >= 80 Then
    grade = "A"
ElseIf mark >= 70 Then
    grade = "B"
ElseIf mark >= 60 Then
    grade = "C"
ElseIf mark >= 50 Then
    grade = "D"
Else
    grade = "F"
End If

lblGrade.Text = $"Mark: {mark}  |  Grade: {grade}"

' Discount calculator with ElseIf
Dim amount As Decimal
Decimal.TryParse(txtAmount.Text, amount)

Dim discount As Double
If amount > 500 Then
    discount = 0.2   ' 20%
ElseIf amount > 200 Then
    discount = 0.1   ' 10%
ElseIf amount > 100 Then
    discount = 0.05  ' 5%
Else
    discount = 0     ' no discount
End If

Dim savings = amount * discount
Dim total   = amount - savings
lblDiscount.Text = $"Discount: {discount:P0}  |  Save: {savings:C}  |  Pay: {total:C}"
Try It — Simulation 13.1: Grade & Discount Calculator

Two classic ElseIf applications — grade classification and discount calculator. See which branch is taken step-by-step.

Grade & Discount Calculator
Grade Calculator
Mark (0-100):
Discount Calculator
Purchase amount (RM):

13.5 Nested If Statements

An If statement can contain another If statement inside it. This is useful for decisions that depend on multiple related conditions. However, deeply nested code becomes hard to read — use it sparingly and prefer flat ElseIf chains where possible.

NestedIf.vb — Visual Basic 2026
' Role-based access control with nested If
If txtUsername.Text <> "" Then
    If txtPassword.Text = GetPassword(txtUsername.Text) Then
        If txtUsername.Text = "admin" Then
            lblStatus.Text = "Admin access granted"
            btnDeleteAll.Visible = True
        Else
            lblStatus.Text = "User access granted"
            btnDeleteAll.Visible = False
        End If
    Else
        lblStatus.Text = "Wrong password"
    End If
Else
    lblStatus.Text = "Username required"
End If

' BETTER: flatten with AndAlso to reduce nesting
If String.IsNullOrWhiteSpace(txtUsername.Text) Then
    lblStatus.Text = "Username required"
    Return
End If

If txtPassword.Text <> GetPassword(txtUsername.Text) Then
    lblStatus.Text = "Wrong password"
    Return
End If

' Reached here: login valid
If txtUsername.Text = "admin" Then
    lblStatus.Text = "Admin access granted"
    btnDeleteAll.Visible = True
Else
    lblStatus.Text = "User access granted"
End If
Tip — Early Return (Guard Clauses)

The "early return" pattern (also called a guard clause) handles error/invalid cases first and returns immediately. The main logic then runs without any nesting. This is the preferred VB 2026 style for input validation and keeps code readable at any scale. Return at the first sign of trouble; don't wrap the entire happy path in nested Ifs.


13.6 Inline If() — The Ternary Operator

The inline If(condition, trueValue, falseValue) evaluates a condition and returns one of two values on a single line. It is the VB 2026 equivalent of the ternary operator ? : in C# and Java.

InlineIf.vb — Visual Basic 2026
' Syntax: If(condition, valueIfTrue, valueIfFalse)
Dim result   = If(score >= 50, "Pass", "Fail")
Dim absValue = If(x >= 0, x, -x)
Dim status   = If(isLoggedIn, "Welcome!", "Please log in")

' Assign in one line
lblResult.Text = If(score >= 50, "Pass", "Fail")

' Use inside string interpolation
lblInfo.Text = $"Status: {If(age >= 18, "Adult", "Minor")}"

' Null-coalescing form: If(obj, fallback)
Dim name = If(txtName.Text, "(unnamed)")
' Returns txtName.Text if non-Nothing, else "(unnamed)"

' Multi-line IIf alternative (old VB6 style -- avoid)
' lblResult.Text = IIf(score >= 50, "Pass", "Fail")  -- evaluates BOTH sides always
' Use If() instead -- short-circuits like AndAlso

' Good use: set a property based on a condition
btnDelete.Enabled = If(lstItems.SelectedIndex >= 0, True, False)
' Simplified:
btnDelete.Enabled = (lstItems.SelectedIndex >= 0)  ' Boolean expression directly
Try It — Simulation 13.2: If..Then..Else Visualiser

Step through how VB 2026 evaluates an If..Then..ElseIf..Else chain — each condition is highlighted as True or False and the matching branch lights up.

If..Then..Else Visualiser
Score (0-100):

13.7 Combining Conditions

Real-world conditions often need multiple criteria checked together. Use AndAlso to require all conditions, OrElse when any one is enough, and Not to invert.

CombinedConditions.vb — Visual Basic 2026
' AndAlso -- ALL conditions must be True
If age >= 18 AndAlso age <= 65 AndAlso hasLicence Then
    lblEligible.Text = "Eligible to drive"
End If

' OrElse -- at least ONE condition must be True
If role = "admin" OrElse role = "manager" Then
    btnApprove.Enabled = True
End If

' Not -- inverts Boolean
If Not String.IsNullOrWhiteSpace(txtEmail.Text) Then
    lblEmailOK.Text = "Email provided"
End If

' Complex: range check + nullable check
If temperature IsNot Nothing AndAlso
   temperature >= 36.0 AndAlso
   temperature <= 37.5 Then
    lblTemp.Text = "Normal body temperature"
ElseIf temperature > 37.5 Then
    lblTemp.Text = "Fever detected"
Else
    lblTemp.Text = "Below normal"
End If

' Boolean flag patterns
Dim isValid = Not String.IsNullOrWhiteSpace(txtName.Text) AndAlso
              Not String.IsNullOrWhiteSpace(txtEmail.Text) AndAlso
              txtEmail.Text.Contains("@")
btnSubmit.Enabled = isValid

13.8 Practical Examples

Example 13.1 — Password Strength Evaluator

PasswordStrength.vb — Visual Basic 2026
Private Sub txtPassword_TextChanged(sender As Object, e As EventArgs) Handles txtPassword.TextChanged
    Dim pwd = txtPassword.Text
    Dim score = 0

    If pwd.Length >= 8                                     Then score += 1
    If pwd.Any(Function(c) Char.IsUpper(c))                Then score += 1
    If pwd.Any(Function(c) Char.IsLower(c))                Then score += 1
    If pwd.Any(Function(c) Char.IsDigit(c))                Then score += 1
    If pwd.Any(Function(c) Not Char.IsLetterOrDigit(c))   Then score += 1

    If score <= 1 Then
        lblStrength.Text = "Weak" : lblStrength.ForeColor = Color.Red
    ElseIf score <= 3 Then
        lblStrength.Text = "Fair" : lblStrength.ForeColor = Color.Orange
    ElseIf score = 4 Then
        lblStrength.Text = "Strong" : lblStrength.ForeColor = Color.Blue
    Else
        lblStrength.Text = "Very Strong" : lblStrength.ForeColor = Color.Green
    End If
End Sub

Example 13.2 — Temperature Converter with Validation

TempConverter.vb — Visual Basic 2026
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
    Dim temp As Double
    If Not Double.TryParse(txtTemp.Text, temp) Then
        lblResult.Text = "Enter a valid temperature."
        Return
    End If

    If rdbCtoF.Checked Then
        Dim fahrenheit = temp * 9 / 5 + 32
        lblResult.Text = $"{temp}°C = {fahrenheit:F1}°F"

        If fahrenheit > 100 Then
            lblNote.Text = "Above boiling point!"
        ElseIf fahrenheit <= 32 Then
            lblNote.Text = "At or below freezing point."
        Else
            lblNote.Text = "Normal temperature range."
        End If
    Else
        Dim celsius = (temp - 32) * 5 / 9
        lblResult.Text = $"{temp}°F = {celsius:F1}°C"
    End If
End Sub
Try It — Simulation 13.3: Login & Access Control

Demonstrates nested If and multi-condition AndAlso. Valid logins: admin/admin123 or user/pass123. Watch the step-by-step condition evaluation.

Login System
Username:
Password:

Try It — Simulation 13.4: Logical Operator Tester

Toggle conditions A and B and see how And, Or, Not, Xor, AndAlso, and OrElse evaluate. Truth table shown live.

Logical Operator Tester
Condition A:
Condition B:

Try It — Simulation 13.5: Full Decision Engine

A practical multi-condition decision engine: loan eligibility checker using age, income, credit score, and existing debt — showing the exact VB 2026 If..ElseIf..Else logic.

Loan Eligibility Checker
Age:
Monthly Income (RM):
Credit Score (300-850):
Existing Monthly Debt (RM):

13.9 GitHub Copilot — Conditional Logic

GitHub Copilot — Input Validator
You typed: ' Validate registration form: name not empty, age 18-99, email contains @ and ., password at least 8 chars with digit. Show specific error for each field.'
' Validate registration form: name not empty, age 18-99, email contains @ and ., password at least 8 chars with digit. Show specific error for each field.
' Clear previous errors
lblNameErr.Text = ""
lblAgeErr.Text  = ""
lblEmailErr.Text = ""
lblPassErr.Text  = ""

Dim isValid = True

' Validate Name
If String.IsNullOrWhiteSpace(txtName.Text) Then
    lblNameErr.Text = "Name is required."
    isValid = False
End If

' Validate Age
Dim age As Integer
If Not Integer.TryParse(txtAge.Text, age) OrElse age < 18 OrElse age > 99 Then
    lblAgeErr.Text = "Age must be between 18 and 99."
    isValid = False
End If

' Validate Email
If Not (txtEmail.Text.Contains("@") AndAlso txtEmail.Text.Contains(".")) Then
    lblEmailErr.Text = "Enter a valid email address."
    isValid = False
End If

' Validate Password
Dim pwd = txtPassword.Text
If pwd.Length < 8 OrElse Not pwd.Any(Function(c) Char.IsDigit(c)) Then
    lblPassErr.Text = "Password needs 8+ characters including a digit."
    isValid = False
End If

If isValid Then
    lblStatus.Text = "Registration successful!"
End If
GitHub Copilot — Tax Bracket Calculator
You typed: ' Malaysian income tax 2026: 0% up to 5000, 1% 5001-20000, 3% 20001-35000, 8% 35001-50000, 14% 50001-70000, 21% above 70000. Annual income from txtIncome.'
' Malaysian income tax 2026: 0% up to 5000, 1% 5001-20000, 3% 20001-35000, 8% 35001-50000, 14% 50001-70000, 21% above 70000. Annual income from txtIncome.
Dim income As Decimal
If Not Decimal.TryParse(txtIncome.Text, income) OrElse income < 0 Then
    lblTax.Text = "Enter a valid income amount."
    Return
End If

Dim taxRate As Double
Dim bracket As String

If income <= 5000 Then
    taxRate = 0    : bracket = "0% (below RM5,000)"
ElseIf income <= 20000 Then
    taxRate = 0.01 : bracket = "1% (RM5,001 - RM20,000)"
ElseIf income <= 35000 Then
    taxRate = 0.03 : bracket = "3% (RM20,001 - RM35,000)"
ElseIf income <= 50000 Then
    taxRate = 0.08 : bracket = "8% (RM35,001 - RM50,000)"
ElseIf income <= 70000 Then
    taxRate = 0.14 : bracket = "14% (RM50,001 - RM70,000)"
Else
    taxRate = 0.21 : bracket = "21% (above RM70,000)"
End If

Dim tax = CDbl(income) * taxRate
lblBracket.Text = $"Bracket: {bracket}"
lblTax.Text     = $"Tax Payable: RM{tax:N2}"
lblNet.Text     = $"Net Income:  RM{CDbl(income) - tax:N2}"
Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while writing conditional logic:

  • "Validate a Malaysian IC number: 12 digits, first 6 are a valid date YYMMDD, 7th digit is state code 01-16"
  • "Build a traffic light controller: if speed > 120 show red warning, > 90 yellow, else green, using Label BackColor"
  • "Create a simple number guessing game: compare guess to secret number with Too High / Too Low / Correct feedback"
  • "Add input validation to every TextBox on the form using If IsNullOrWhiteSpace checks before form submission"

Lesson Summary

  • Use If..Then for one-way decisions, If..Then..Else for two-way, and If..Then..ElseIf..Else for multi-way. Only the first matching branch executes.
  • Always use AndAlso and OrElse (short-circuit) instead of And/Or — they skip evaluating the right side when the result is already determined, preventing null-reference crashes.
  • The early return (guard clause) pattern handles invalid inputs at the top of a procedure with Return, keeping the main logic flat and readable without deep nesting.
  • The inline If(condition, trueValue, falseValue) returns a value in a single expression — use it for simple assignments and property settings. Prefer it over the legacy IIf() which evaluates both sides.
  • Check objects with IsNot Nothing before accessing their members, always using AndAlso to short-circuit: If obj IsNot Nothing AndAlso obj.Value > 0.
  • Use TryParse with a conditional before any numeric operation to avoid exceptions: If Not Integer.TryParse(txt, n) Then Return.
  • GitHub Copilot excels at generating ElseIf chains for classification problems — describe the ranges and labels in a comment and it generates the full structure.

Exercises

Exercise 13.1 — Grade Classifier

  • Enter a mark (0-100) and classify it: A+ (≥90), A (≥80), B (≥70), C (≥60), D (≥50), F (<50)
  • Show the grade in a Label with a matching BackColor (green for pass, red for fail)
  • Validate: reject non-numeric input and values outside 0-100 with specific error messages
  • Display a motivational message: "Excellent!", "Good job!", "Keep trying!", etc. using nested If
  • Copilot challenge: Ask Copilot to "add a class average tracker using an array of marks entered so far"

Exercise 13.2 — Temperature Health Monitor

  • Read a body temperature in °C from a TextBox
  • Classify: <36.0 = Hypothermia, 36.0-37.5 = Normal, 37.6-38.5 = Low Fever, 38.6-40.0 = High Fever, >40.0 = Dangerous
  • Show coloured status Labels and a recommended action for each category
  • Add a RadioButton to switch between °C and °F input using an If..Then..Else for conversion
  • Copilot challenge: Ask Copilot to "log each temperature reading with timestamp to a ListBox"

Exercise 13.3 — Multi-Field Registration Validator

  • Create a registration form with Name, Age, Email, Password, and Confirm Password fields
  • Validate each field with specific If checks and display individual error Labels
  • Password and Confirm Password must match — use If txtPass.Text <> txtConfirm.Text
  • Enable the Register button only when all fields pass validation (use Boolean flag + If chain)
  • Copilot challenge: Ask Copilot to "add real-time validation as the user types using TextChanged event handlers"

Next: Lesson 14 — Select Case

Learn Select Case — VB 2026's cleaner alternative to long ElseIf chains — with case ranges, multiple values per case, and the powerful Select Case True pattern.

Continue »

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Step-by-step coverage of If..Then..Else with practical decision-making projects including validators and classifiers.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 fully-explained VB.NET programs including decision-making applications with complex condition logic.

View on Amazon →