user2087008
user2087008

Reputation:

How use a variable case select?

I have the following code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Select Case TextBox1.Text
        Case TextBox1.Text.Contains("string")
            MsgBox("tb 1 contains string")
        Case Else
            Msgbox("Invalid command")
    End Select
End Sub

However, I am not sure how to make the case select work in this way, I am trying to make it so that if textbox 1 contains "string" when button 1 is pressed, a msgbox let's the user know. There are no errors thrown by VS, and I can't work out if this is valid code or I'm doing it incorrectly.

Upvotes: 1

Views: 1431

Answers (4)

pcreech
pcreech

Reputation: 334

Case statements by design are supposed to have defined constant values. With the small complexity of your logic, it would be better to use an if/else statement instead.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text.Contains("string") Then
        MsgBox("tb 1 contains string")
    Else
        Msgbox("Invalid command")
    End If
End Sub

Upvotes: 2

igrimpe
igrimpe

Reputation: 1785

Simply make it

Select Case True
    Case tb1.Text = "foo" And tb2.Text = "bar" : MsgBox("42")
    Case tb1.Text = "foo" : MsgBox("Missing the bar?")
    Case tb2.Text = "bar" : MsgBox("Without a foo?")
    Case Else : MsgBox("fubar!")
End Select

this gives you the freedom to switch on almost everything.

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You can't use variable as case value. It has to be a constant value. Use If/Else statements instead.

If TextBox1.Text.Contains("string") Then
    MsgBox("tb 1 contains string")
Else
    Msgbox("Invalid command")
End If

Of using short version of If:

MsgBox(If(TextBox1.Text.Contains("string"), "tb 1 contains string", "Invalid command"))

Upvotes: 0

Victor Zakharov
Victor Zakharov

Reputation: 26424

Taking all existing answers into account, here is how I would write it:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim msg As String = GetMessage(TextBox1.Text)
  MessageBox.Show(msg)
End Sub

Private Function GetMessage(text As String) As String
  If text.Contains("string") Then Return "tb 1 contains string"
  Return "Invalid command"
End Function

Upvotes: 0

Related Questions