Reputation: 101
I'm trying to satisfy all the cases of multiple check boxes being checked at the same time. The first four 'if' statements are setting the values of each check box. Then I have started trying to do a Select-Case for multiple check boxes but it's not working. Just wondering if there is a more efficient way of doing this? Thanks.
If chkCut.Checked = True Then
serviceRate = 30.0
End If
If chkColour.Checked = True Then
serviceRate = 40.0
End If
If chkHighlights.Checked = True Then
serviceRate = 50.0
End If
If chkExtensions.Checked = True Then
serviceRate = 200.0
End If
Dim i As Integer
Select Case i
Case chkCut.Checked And chkColour.Checked
i = baseRate + 70.0
Case chkCut.Checked And chkHighlights.Checked
i = baseRate + 80.0
Case chkCut.Checked And chkExtensions.Checked
i = baseRate + 230.0
Upvotes: 0
Views: 3282
Reputation: 112762
You want to have the sum of the selected values, therefore sum up the selected values.
serviceRate = 0.0
If chkCut.Checked Then
serviceRate += 30.0
End If
If chkColour.Checked Then
serviceRate += 40.0
End If
' Do the same for the other checkboxes
...
The expression serviceRate += 30.0
is a shorthand form of serviceRate = serviceRate + 30.0
.
If you have 4 checkboxes you have 2 × 2 × 2 × 2 = 24 = 16 ways of checking or not checking them. A very tedious task with Select Case
!
Btw: The Select...Case Statement selects one case according to a given value. This is not what you tried to do. You should have used an If...Then...Else Statement statement. However, this is obsolete now.
Upvotes: 1
Reputation: 5380
The Linq geek in me would do something like this:
Subclass CheckBox and add a Rate
property:
Public Class RateCheckBox
Inherits CheckBox
Private _Rate As Decimal
Public Property Rate() As Decimal
Get
Return _Rate
End Get
Set(ByVal value As Decimal)
_Rate = value
End Set
End Property
End Class
Then in the form, I'd have a button click handler and helper function like this:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Rate As Decimal = CalcRate()
Label1.Text = Rate.ToString()
End Sub
Private Function CalcRate() As Decimal
Return Me.Controls.OfType(Of RateCheckBox).Where(Function(c) c.Checked).Sum(Function(c) c.Rate)
End Function
End Class
Now, when you create your form, you can use your own RateCheckBox
class instead of the regular CheckBox
, and in the designer's property window, you can set the rate associated to each checkbox.
What I like about this approach is that it's scalable, meaning that no matter how many checkboxes you add to the form, it will always calculate the right amount without you having to change the calculation function.
Cheers
Upvotes: 0