SamCramphorn
SamCramphorn

Reputation: 143

Is there an alternative method to using 15 If statements?

I have 15 items in my ComboBox and when the user selects an item I want to present something different in my TextBox.

At the moment I have:

If cb_dropdown.SelectedIndex = 0 Then
    RTB_Sql.Text = "update access
set accessdesc = 'Less than 5' where accessID < '5'"
Else
    If cb_dropdown.SelectedIndex = 1 Then
        RTB_Sql.Text = "update access
set accessdesc = 'More than 5' where accessID > '5' and < '10' "
    Else
        If cb_dropdown.SelectedIndex = 2 Then
            RTB_Sql.Text = ""

etc....

Is there a nicer and more methodical way to approach this as it looks quite scruffy?

Upvotes: 0

Views: 98

Answers (2)

shadow
shadow

Reputation: 1903

You can also use something like this if you want to check range of values:

Sub Main()
        Dim i As Integer = 6

        Select Case True
            Case 0 <= i AndAlso i < 5
                Console.WriteLine("i is between 0 and 4")

            Case 6 <= i
                Console.WriteLine("i is 6 or greater")
        End Select



        Console.ReadLine()
    End Sub

Be aware that it stops in the first true condition.

Upvotes: 0

Tedd Hansen
Tedd Hansen

Reputation: 12314

Yes, it is called select.

Select Case cb_dropdown.SelectedIndex
    Case 0 To 4
        RTB_Sql.Text = "update access
set accessdesc = 'Less than 5' where accessID < '5'"
    Case 5
        RTB_Sql.Text = [...]
    Case Else
        RTB_Sql.Text = [...]
End Case

Although in your case I think what you are looking for is < (less than) and > (greater than).

If cb_dropdown.SelectedIndex < 5 Then
    RTB_Sql.Text = "update access set accessdesc = 'Less than 5' where accessID < '5'"
ElseIf cb_dropdown.SelectedIndex < 10 Then
    RTB_Sql.Text = "update access set accessdesc = 'More than 5' where accessID > '5' and < '10' "
End If

Not really sure what you are trying to do though. Maybe if you explain in more detail someone can provide a better answer. So let me take a wild guess:

Dim n As Integer = cb_dropdown.SelectedIndex * 5
RTB_Sql.Text = "update access set accessdesc = 'More than " + n + "' where accessID > '" + n + "' and < '" + (n+6) + "' "

This will give you the following result based on SelectedIndex:

  • 0 = from 1 to including 5
  • 1 = from 6 to including 10
  • etc...

If you want to shift it down one (include 0 and not 5 in first batch) then just change > to >= and 6 to 5.

Upvotes: 3

Related Questions