SOPMOD
SOPMOD

Reputation: 31

When x number of checkboxes are checked do x to the rest

enter image description here

Hello everyone so I'm having trouble figuring out how I could check if 3 checkboxes inside the GroupBox called "Toppings" are checked. I'll have to make it so it adds a certain amount after that to the total when a different size pizza is checked but that I could try to figure out myself. I figured out how I could make it work but it's not universal so all the checkboxes could use it.

If CheckBox1.Checked = True Then
    lblTest.Text = 1
Else
    If lblTest.Text <= 0 Then
        lblTest.Text = 0
    Else
        lblTest.Text -= lblTest.Text
    End If
End If

The use of the label is just for testing purposes to see if I could get it to 3 and back to 0 when checking and unchecking. I would like to get a method going where it checks for the change in the checkbox and adds 1 to a variable called TopNum. This is so when it reaches 3 it turns on a bool called fTop so every other checkbox after that gets added to the total. This could then help me figure out how I could apply it to the pizza size giving it different prices amounts on the toppings by adding a multiplier.

Upvotes: 0

Views: 90

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

Given a GroupBox named Toppings and an Integer field named TopNum, I would do this:

TopNum = Toppings.Controls.OfType(Of CheckBox)().Count(Function(cb) cb.Checked)
If TopNum >= 3 Then
    '...
End If

You can put that in the CheckChanged event handler for all of the checkboxes. Or better, all of the checkboxes can have the same event handler, which has this code.

Also, I'd probably remove the If conditional and change TopNum from a field to a property. Then the If conditional would go in the property setter.

Public Property TopNum As Integer
   Get
       Return _topNum
   End Get
   Set (value As Integer)
        _topNumn = value
        If value >= 3 Then
             '...
        Else
             '...
        End If
   End Set
End Property
Private _topNum As Integer = 0        

Public Sub ToppingsChanged(sender As Object, e As EventArgs) 
    TopNum = Toppings.Controls.OfType(Of CheckBox)().Count(Function(cb) cb.Checked)
End Sub

Public Sub New()
   IntializeComponent()

    For Each cb As CheckBox In Me.Controls.OfType(Of CheckBox)()
       AddHandler cb, AddressOf ToppingsChanged
    Next
End Sub

Upvotes: 2

Related Questions