Commandos
Commandos

Reputation: 37

Visual Basic How to get sum of all checked checkboxes

I have given each checkbox item on my application a value. I have group of checkboxes and I need to add up their total value base on user selection. I am using this code but it's not working for sum. I do not want to use if a.checked then add this elseif this checked add that kind of way.

   Dim abe As CheckBox = groupAlumni.Controls.OfType(Of CheckBox)().Where(Function(r) r.Checked = True).Sum()
    MsgBox(abe.Tag)

.sum part is giving an error. How can I achieve this?

Option 2 Also I am thinking I could change checkbox names to cb0 to cb15 and create a while loop and check them one by one to see which ones are selected and add up their values. How can I change cb number during while loop?

I wrote this but I really need cb0 to be cb1,cb2 and continue until cb15 during the loop.

If anybody answers either option it's fine for me. Thank you!

    Dim counter As Integer = 0
    Dim cbScore As Integer = 0

    While counter < 15
        If cb0.Checked Then
            cbScore += cb0.Tag
        End If

        counter += 1
    End While

Upvotes: 0

Views: 2710

Answers (2)

hallowedzen
hallowedzen

Reputation: 1

Removed due to not compiling and incompatible methods.

Upvotes: -1

Stijn
Stijn

Reputation: 2060

If you only need the sum of the values, try this:

cbScore = groupAlumni.Controls.OfType(Of CheckBox)().Where(Function(r) r.Checked).Sum(Function(r) CInt(r.Tag))

Upvotes: 3

Related Questions