Select Case
Master VB 2026's cleaner alternative to long ElseIf chains — exact value matching, comma-separated value lists, ranges with To, comparisons with Is, string pattern matching, the powerful Select Case True pattern, and when to choose Select Case over If..ElseIf.
Select Case when you are comparing one expression against many possible values — it is more readable and typically faster than an equivalent ElseIf chain. VB 2026's Select Case supports exact values, comma-separated lists, ranges (To), and comparison operators (Is >=). The Select Case True pattern elegantly handles complex boolean conditions. Always include a Case Else for safety — it catches unexpected values that would otherwise be silently ignored.
14.1 Basic Select Case Syntax
The expression after Select Case is evaluated once. VB 2026 then compares it against each Case clause top-to-bottom and executes the first match. Unlike C#/Java switch, there is no fall-through — once a case matches, the rest are skipped automatically.
' Syntax Select Case expression Case value1 ' runs when expression = value1 Case value2 ' runs when expression = value2 Case Else ' runs when no Case matched End Select ' Day of week example Dim day = DateTime.Now.DayOfWeek Select Case day Case DayOfWeek.Monday lblDay.Text = "Start of the work week" Case DayOfWeek.Wednesday lblDay.Text = "Midweek" Case DayOfWeek.Friday lblDay.Text = "TGIF!" Case DayOfWeek.Saturday, DayOfWeek.Sunday lblDay.Text = "Weekend" Case Else lblDay.Text = "Regular weekday" End Select ' Menu selection with Integer Dim choice As Integer Integer.TryParse(txtChoice.Text, choice) Select Case choice Case 1 : lblAction.Text = "New file" Case 2 : lblAction.Text = "Open file" Case 3 : lblAction.Text = "Save file" Case 4 : lblAction.Text = "Exit" Case Else : lblAction.Text = "Invalid option" End Select
In C# and Java, forgetting a break in a switch causes code to "fall through" to the next case — a common bug. VB 2026's Select Case has no fall-through. Each matched case runs its block and exits automatically. This makes VB's Select Case safer by default.
14.2 Case Matching Patterns
VB 2026's Case clause supports four matching styles that can be used in the same Select Case block.
| Pattern | Syntax | Example | Matches when |
|---|---|---|---|
| Exact value | Case value | Case 5 | expression = 5 |
| Value list | Case v1, v2, v3 | Case 1, 3, 5 | expression is any listed value |
| Range | Case low To high | Case 1 To 10 | low ≤ expression ≤ high |
| Comparison | Case Is op value | Case Is >= 90 | expression satisfies the operator |
Dim score As Integer = 82 ' Mix of exact, range, comparison, and list in same block Select Case score Case Is >= 90 ' comparison: Is operator lblGrade.Text = "A+" Case 80 To 89 ' range: 80 through 89 inclusive lblGrade.Text = "A" Case 70 To 79 lblGrade.Text = "B" Case 60 To 69 lblGrade.Text = "C" Case 50 To 59 lblGrade.Text = "D" Case Is < 0 ' comparison: below zero is invalid lblGrade.Text = "Invalid" Case Else ' anything else (below 50) lblGrade.Text = "F" End Select ' Value list -- month classification Dim month = DateTime.Now.Month Select Case month Case 3, 4, 5 ' list: March, April, May lblSeason.Text = "Spring" Case 6, 7, 8 lblSeason.Text = "Summer" Case 9, 10, 11 lblSeason.Text = "Autumn" Case 12, 1, 2 lblSeason.Text = "Winter" Case Else lblSeason.Text = "Unknown month" End Select ' String matching -- case-insensitive in VB by default Dim command = txtCommand.Text.Trim().ToLower() Select Case command Case "quit", "exit", "bye" Application.Exit() Case "help", "?" ShowHelp() Case "new" NewDocument() Case Else lblStatus.Text = $"Unknown command: {command}" End Select
Enter a score and see which Case clause matches — each clause is highlighted as MATCH or SKIP, showing the exact pattern that fired.
14.3 Select Case vs If..ElseIf
Both structures solve multi-way decisions. Choose the right one based on the problem shape.
If score >= 90 Then grade = "A+" ElseIf score >= 80 Then grade = "A" ElseIf score >= 70 Then grade = "B" ElseIf score >= 60 Then grade = "C" Else grade = "F" End If
Select Case score Case Is >= 90 grade = "A+" Case 80 To 89 grade = "A" Case 70 To 79 grade = "B" Case 60 To 69 grade = "C" Case Else grade = "F" End Select
| Use Select Case when… | Use If..ElseIf when… |
|---|---|
| Comparing one variable against many values | Each condition tests a different variable |
| You have 4+ branches on the same expression | You only have 2–3 branches |
| Values are discrete (menu items, day numbers, strings) | Conditions involve different expressions combined with AndAlso/OrElse |
| Ranges and value lists are natural fits | You need short-circuit evaluation (AndAlso) |
14.4 Select Case True — The Power Pattern
Select Case True evaluates each Case as a Boolean expression and runs the first one that is True. This combines the readability of Select Case with the flexibility of If..ElseIf for complex conditions.
' Select Case True: each Case is a Boolean expression Dim age As Integer = 25 Dim income As Decimal = 4500 Select Case True Case age < 18 lblCategory.Text = "Minor -- not eligible" Case age >= 18 AndAlso income < 2000 lblCategory.Text = "Young adult, low income" Case age >= 18 AndAlso income >= 2000 AndAlso income < 5000 lblCategory.Text = "Adult, medium income" Case age >= 18 AndAlso income >= 5000 lblCategory.Text = "Adult, high income" Case Else lblCategory.Text = "Unknown category" End Select ' BMI classification using Select Case True Dim bmi = weight / (height ^ 2) Select Case True Case bmi < 18.5 lblBMI.Text = "Underweight" lblBMI.ForeColor = Color.Blue Case bmi < 25.0 lblBMI.Text = "Normal weight" lblBMI.ForeColor = Color.Green Case bmi < 30.0 lblBMI.Text = "Overweight" lblBMI.ForeColor = Color.Orange Case Else lblBMI.Text = "Obese" lblBMI.ForeColor = Color.Red End Select
The Select Case True pattern is preferred when you have 4+ branches that each test a different Boolean condition. It reads as a clean list of named outcomes rather than a chain of ElseIfs, making the intent of each branch immediately obvious at a glance.
14.5 Practical Examples
Example 14.1 — Calculator with Operator Select
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click Dim a, b As Double If Not Double.TryParse(txtA.Text, a) OrElse Not Double.TryParse(txtB.Text, b) Then lblResult.Text = "Enter valid numbers." : Return End If Dim op = cboOp.Text ' "+", "-", "*", "/" Dim result As Double Select Case op Case "+" : result = a + b Case "-" : result = a - b Case "*" : result = a * b Case "/" If b = 0 Then lblResult.Text = "Cannot divide by zero." : Return End If result = a / b Case "^" : result = Math.Pow(a, b) Case "Mod" : result = a Mod b Case Else lblResult.Text = "Select an operator." : Return End Select lblResult.Text = $"{a} {op} {b} = {result:G}" End Sub
Example 14.2 — Role-Based Menu System
Private Sub SetupMenuForRole(role As String) ' First hide everything mnuAdmin.Visible = False mnuManager.Visible = False mnuReports.Visible = False mnuBasic.Visible = True ' always visible Select Case role.ToLower() Case "admin" mnuAdmin.Visible = True mnuManager.Visible = True mnuReports.Visible = True lblRole.Text = "Administrator -- Full Access" Case "manager" mnuManager.Visible = True mnuReports.Visible = True lblRole.Text = "Manager -- Standard Access" Case "staff", "employee" mnuReports.Visible = True lblRole.Text = "Staff -- Limited Access" Case "guest" lblRole.Text = "Guest -- Read-Only" Case Else lblRole.Text = "Unknown role -- access denied" Application.Exit() End Select End Sub
Select Case on a string operator — enter two numbers and pick an operator to see the matching Case branch execute.
Demonstrates value lists and ranges on integer values — day of week and month classification.
14.6 String Select Case
Select Case works seamlessly with strings. By default VB compares strings case-insensitively when the Option Compare Text module setting is used, or you can .ToLower() the expression for guaranteed case-insensitive matching.
' HTTP status code handler Dim statusCode As Integer = httpResponse.StatusCode Select Case statusCode Case 200 lblStatus.Text = "200 OK" : lblStatus.ForeColor = Color.Green Case 201 lblStatus.Text = "201 Created" : lblStatus.ForeColor = Color.Green Case 301, 302 lblStatus.Text = "3xx Redirect" : lblStatus.ForeColor = Color.Orange Case 400 lblStatus.Text = "400 Bad Request" : lblStatus.ForeColor = Color.Red Case 401, 403 lblStatus.Text = "Auth error" : lblStatus.ForeColor = Color.Red Case 404 lblStatus.Text = "404 Not Found" : lblStatus.ForeColor = Color.Red Case 500 lblStatus.Text = "500 Server Error" : lblStatus.ForeColor = Color.DarkRed Case Is >= 200, Is <= 299 lblStatus.Text = "2xx Success" : lblStatus.ForeColor = Color.Green Case Else lblStatus.Text = $"Status: {statusCode}" End Select ' File extension handler using string Select Case Dim ext = System.IO.Path.GetExtension(fileName).ToLower() Select Case ext Case ".jpg", ".jpeg", ".png", ".gif", ".bmp" imgViewer.Load(fileName) lblType.Text = "Image file" Case ".txt", ".md", ".csv" txtEditor.Text = File.ReadAllText(fileName) lblType.Text = "Text file" Case ".vb", ".cs", ".py", ".js" txtEditor.Text = File.ReadAllText(fileName) lblType.Text = "Source code" Case Else lblType.Text = $"Unsupported: {ext}" End Select
Demonstrates Select Case True where each Case is a Boolean expression — BMI classifier and income bracket calculator side by side.
String Select Case driving a role-based access control system — each role unlocks a different set of buttons.
14.7 GitHub Copilot — Select Case Patterns
' Handle HTTP status codes: group 2xx as success, 3xx as redirect, 4xx as client error, 5xx as server error. Show appropriate message and icon in lblStatus.'' Handle HTTP status codes: group 2xx as success, 3xx as redirect, 4xx as client error, 5xx as server error. Dim code As Integer If Not Integer.TryParse(txtStatusCode.Text, code) Then lblStatus.Text = "Invalid status code." : Return End If Select Case code Case 200 : lblStatus.Text = "OK" Case 201 : lblStatus.Text = "Created" Case 204 : lblStatus.Text = "No Content" Case 200 To 299 lblStatus.Text = $"Success ({code})" picIcon.Image = imgSuccess Case 301, 302, 307, 308 lblStatus.Text = $"Redirect ({code})" picIcon.Image = imgRedirect Case 400 : lblStatus.Text = "Bad Request" Case 401 : lblStatus.Text = "Unauthorized" Case 403 : lblStatus.Text = "Forbidden" Case 404 : lblStatus.Text = "Not Found" Case 400 To 499 lblStatus.Text = $"Client Error ({code})" picIcon.Image = imgError Case 500 : lblStatus.Text = "Internal Server Error" Case 500 To 599 lblStatus.Text = $"Server Error ({code})" picIcon.Image = imgServerError Case Else lblStatus.Text = $"Unknown: {code}" End Select
' Currency converter: Select Case on currency code string. Support MYR, USD, EUR, GBP, JPY, SGD. Base currency is MYR. Show converted amount.'' Currency converter: Select Case on currency code string. Base currency is MYR. Dim amount As Decimal If Not Decimal.TryParse(txtAmount.Text, amount) OrElse amount <= 0 Then lblResult.Text = "Enter a positive amount." : Return End If Dim currency = cboCurrency.SelectedItem.ToString().ToUpper() Dim rate As Double Dim symbol As String Select Case currency Case "MYR" : rate = 1.0 : symbol = "RM" Case "USD" : rate = 0.213 : symbol = "$" Case "EUR" : rate = 0.197 : symbol = "€" Case "GBP" : rate = 0.169 : symbol = "£" Case "JPY" : rate = 32.1 : symbol = "¥" Case "SGD" : rate = 0.285 : symbol = "S$" Case Else lblResult.Text = $"Currency '{currency}' not supported." Return End Select Dim converted = CDbl(amount) * rate lblResult.Text = $"RM {amount:N2} = {symbol}{converted:N2} ({currency})" lblRate.Text = $"Rate: 1 MYR = {rate:G} {currency}"
Try these in the Copilot Chat panel while writing Select Case code:
- "Convert a grade letter (A+, A, B, C, D, F) back to a numeric GPA value using Select Case on a String"
- "Build a postcode state lookup: given the first 2 digits, return the Malaysian state name using Select Case with ranges"
- "Create a simple state machine for a traffic light: Green/Yellow/Red with a timer, use Select Case on the current state"
- "Use Select Case True to classify a product price into Budget/Mid-range/Premium/Luxury tiers"
Lesson Summary
Select Caseevaluates an expression once and compares it against each Case clause. The first match executes; there is no fall-through. Always includeCase Elseto handle unexpected values.- Four matching patterns: exact value (
Case 5), value list (Case 1, 3, 5), range (Case 1 To 10), comparison (Case Is >= 90). These can be mixed in one block. - Select Case is preferred over If..ElseIf when comparing one expression against 4+ values, especially with discrete values, ranges, or lists. Use If..ElseIf when conditions involve different variables combined with AndAlso/OrElse.
Select Case Trueis a powerful pattern where eachCaseis a Boolean expression — combines the readability of Select Case with the flexibility of If..ElseIf for complex conditions.- String Select Case is case-insensitive by default with
Option Compare Text. For guaranteed case-insensitive matching, call.ToLower()on the expression before theSelect Case. - Comma-separated value lists in a single Case (
Case "quit", "exit", "bye") are more readable and efficient than multiple separate Cases for the same action. - GitHub Copilot generates complete Select Case blocks from a comment describing the values and their actions — ideal for lookup tables, state machines, and role-based access patterns.
Exercises
Exercise 14.1 — Simple Calculator
- Build a calculator with two TextBoxes (A, B) and a ComboBox for operator (+, -, *, /, ^, Mod)
- Use Select Case on the operator string to perform the correct calculation
- Handle division by zero with an If check inside the Case "/" block
- Display the full expression and result: "12 * 4 = 48"
- Copilot challenge: Ask Copilot to "add a history ListBox that stores the last 10 calculations"
Exercise 14.2 — Malaysian Postcode State Finder
- Enter a 5-digit Malaysian postcode in a TextBox
- Extract the first 2 digits and use
Select CasewithToranges to identify the state - Ranges: 01–02 Perlis, 05–09 Kedah, 10–14 Penang, 15–18 Kelantan, 20–24 Terengganu, 25–28 Pahang, 30–34 Perak, 35–36 Perak, 40–68 Selangor/KL, 70–73 Negeri Sembilan, 75–77 Malacca, 80–86 Johor
- Show the state name and a fun fact about the state
- Copilot challenge: Ask Copilot to "add Sabah/Sarawak postcodes (88xxx-98xxx) with their districts"
Exercise 14.3 — Traffic Light State Machine
- Create a form with a PictureBox showing Red/Yellow/Green coloured circles
- Use
Select Caseon a String state variable ("Red", "Yellow", "Green") - A Timer advances the state: Red → Green → Yellow → Red with different durations
- Show a Label: "STOP", "GO", "SLOW DOWN" matching the current state
- Copilot challenge: Ask Copilot to "add a pedestrian crossing button that inserts a Walk state after Red"
Related Resources
← Lesson 13
If..Then..Else — conditional logic and logical operators.
Lesson 15 →
Looping — For..Next, For Each, Do While, Do Until.
MS Docs — Select Case
Complete VB.NET language reference including all Case patterns.
MS Docs — Decision Structures
When to use Select Case vs If..ElseIf — official guidance.
Featured Books
Visual Basic 2022 Made Easy
Covers Select Case with practical menu systems, state machines, and multi-condition decision programs.
View on Amazon →
VB Programming With Code Examples
48 fully-explained VB.NET programs including role-based access, calculators, and lookup-table patterns.
View on Amazon →