Hello programmers!

I want small help with code. I want something to happen when text in TextBox1 is A or B or C without writing same code 3 times. I don't know how to write it. I tried with it:

If TextBox1.Text = "A" or "B" or "C" Then
    'Event
End if

Thanks.

Dani AI

Generated

wanted a concise way to run the same block when TextBox1.Text is one of several values. 's explicit OR works but gets verbose as the list grows, and 's array/regex ideas point in the right directions. Two clean, maintainable approaches follow: one for short lists (readability), one for larger/configurable sets (performance/maintainability).

Select Case keeps intent clear and is ideal for a small set of literal values:

Select Case TextBox1.Text.Trim()
    Case "A", "B", "C"
        ' event code here
End Select

A collection lookup scales better and avoids repeated text comparisons. Using a HashSet with a case-insensitive comparer gives fast O(1) checks and is handy when values are loaded from config or a database:

Dim allowed = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) From {"A", "B", "C"}
If allowed.Contains(TextBox1.Text.Trim()) Then
    ' event code here
End If

Practical notes and traps observed in similar threads:

  • Trim input and handle empty/null (use String.IsNullOrWhiteSpace) before testing.
  • Decide case sensitivity up front: StringComparer.OrdinalIgnoreCase or normalize with ToUpperInvariant()/ToLowerInvariant() to avoid mismatches.
  • Regex (as suggested) is good for patterns, but is overkill for literal lists and can be harder to read/maintain.
  • For tiny, one-off checks the explicit OR is acceptable; for anything reused or configurable prefer Select Case or a collection.

These options keep the event code in one place and make future changes (adding/removing allowed values) straightforward.

Recommended Answers

All 2 Replies

Try

If TextBox1.Text = "A" Or TextBox1.Text = "B" Or TextBox1.Text = "C" Then
    'Do Work
End If

There's no magic way to do it, but there's others ways like storing the values A,B,C in an array and loop for a match or using RegEx.

I'd use RegEx for a short code, something like this:

IF ( RegEx.Match(TextBox1.Text, "^[ABC]$").Success ) Then

End If

To use RegEx you need to import System.Text.RegularExpressions.

commented: Nice +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.