How to Add Not condition in the below select case.
Is <> works for single value, and 'To' works for a Range but the value are specific values there are not series of numbers. Is it possible to use select case in this scenario, or do i have to switch to if-else. Ex: i don't want case to execute when value is 0 and 3
Select value
case 0,1,2,3
End Select
I'm not sure I understand the question...
Why can't you just write the example code like so:
Select Case value
Case 1, 2
DoWork()
End Select
Nothing gets executed when value = 0
or value = 3
. The series of values provided to a Case
statement doesn't have to be sequential.
Update in response to comment:
I would write that like this, taking advantage of the Case Else
label:
Select Case myComboBox.SelectedIndex
Case 1, 5, 8
'The suggestion is acceptable, so process it
DoWork()
Case Else
'The suggestion is invalid, so show an error
MessageBox.Show("You cannot select that option. " & _
"Please choose options 1, 5, or 8 instead.", _
"Invalid Selection", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Select
Of course, if you don't actually have any "work" to be done in the case that the user selects the correct value, there seems little point in using a Select Case
statement at all. The cardinal rule should be to use whichever makes your code the clearest and easiest to understand. There's little validity to the suspicion that Select Case
is faster than an If
statement—the compiler is smart enough to produce virtually equivalent results in almost every case.
Building on what Cody wrote I would go with:
Select Case value
Case 1, 2
DoWork()
Case 0 ,3
'nothing to do, only log if needed
Case Else
Debug.Fail("Please provide a logical path for all possible values")
End Select
The extra branches are just to clarify the intent of the code and to guard against future changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With