Results 1 to 3 of 3

Thread: counting checked boxes

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2013
    Posts
    23

    counting checked boxes

    Ok, I have two forms. The first form you enter in a whole bunch of info and have a row of checked boxes. Once you click submit, the second form pops up calculating every thing entered on the first form and a has the total number of checked boxes clicked. I am having trouble getting the sum of the checked boxes. First I tried to get the result in textbox but that didnt work. So I made box be a listview so I could you the function count, but it doesn't work on counting items on the first form. Any ideas?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: counting checked boxes

    The second form should not be doing any of that. The second form should be for display only. If the controls are on the first form then the first form should be doing the counting and then simply passing that count to the second form for display and/or some other use. All forms should be responsible for themselves.

    As for counting the checked CheckBoxes, assuming that they are all in the same container and there are none to be excluded then this is the easiest way:
    Code:
    Dim checkedBoxCount = Controls.OfType(Of CheckBox)().Count(Function(cb) cb.Checked)
    That will count the checked CheckBoxes on the form itself. If they are in a Panel or GroupBox or some other container then use its Controls collection instead. Here's the long form of that code:
    Code:
    Dim checkedBoxCount As Integer
    
    For Each ctrl As Control In Controls
        Dim cb = TryCast(ctrl, CheckBox)
    
        If cb IsNot Nothing AndAlso cb.Checked Then
            checkedBoxCount += 1
        End If
    Next
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Apr 2013
    Posts
    23

    Re: counting checked boxes

    Thanks so much! it definitely helped!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width