amazen123
amazen123

Reputation: 23

VB.net if else convert to case select

hi guys can you help me to convert this to case select statement, this is my first time using case select statement.

If TabControl1.SelectedTab Is tp_5 Then
      myqry = "SELECT * FROM TBLVLAN5 ORDER BY ID"
ElseIf TabControl1.SelectedTab Is tp_7 Then
      myqry = "SELECT * FROM TBLVLAN7 ORDER BY ID"

i search in web but i only found case select statement using integer and string and not the one that fit with my if else example.

i also try use it but its not working, this is my code.

Dim h As String
    h = TabControl1.SelectedTab Is tp_10
    Select Case h
        Case TabControl1.SelectedTab Is tp_5
            myqry = "SELECT * FROM TBLVLAN5 ORDER BY ID"
        Case TabControl1.SelectedTab Is tp_7
            myqry = "SELECT * FROM TBLVLAN7 ORDER BY ID"
        Case TabControl1.SelectedTab Is tp_8
            myqry = "SELECT * FROM TBLVLAN8 ORDER BY ID"
    End Select

any help is greatly appreciated. thanks.

Upvotes: 2

Views: 1341

Answers (3)

hello_world
hello_world

Reputation: 432

You could remove the need for an If or a Case statement.

If you set the name property of the tabs to something like "tab_5", you could set myqry string by:

myqry = "SELECT * FROM TBLVLAN" + TabControl1.SelectedTab.Name.Split("_")[1] + " ORDER BY ID"

This would take the number part of the Tab name and put it in the sql query string.

Upvotes: 1

Patrick McDonald
Patrick McDonald

Reputation: 65431

One possible solution is as follows:

Select Case True
    Case TabControl1.SelectedTab Is tp_5
        myqry = "SELECT * FROM TBLVLAN5 ORDER BY ID"
    Case TabControl1.SelectedTab Is tp_7
        myqry = "SELECT * FROM TBLVLAN7 ORDER BY ID"
End Select

It's up to you to decide if this is more readable than the If..Then..Else :)

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460158

You cannot use a Select...Case to compare references with Is, use the If...Else:

If TabControl1.SelectedTab Is tp_5 Then
      myqry = "SELECT * FROM TBLVLAN5 ORDER BY ID"
ElseIf TabControl1.SelectedTab Is tp_7 Then
      myqry = "SELECT * FROM TBLVLAN7 ORDER BY ID"  
...
End If

As an aside, i warmly recommend to set Option Strict to ON.

Dim h As String doesn't compile then because because Is tp_10 returns a Boolean. Option Strict prevents you from incorrect magic compiler conversions that aren't desired.

Upvotes: 2

Related Questions