Click here to Skip to main content
15,300,160 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have 20 labels and a checkbox in front of each of them (totally, 20 checkboxes). Each label has a random number. I want to sum up numbers checked by pressing a button.
How can I do this? (This is just an example, I'd use the answer to solve my own problem in my project)

What I have tried:

One way is to use nested If or Switch for checked items. But it doesn't make sense in large projects.
Posted
Updated 1-Apr-21 2:36am
v3
Comments
CHill60 1-Apr-21 8:04am
   
That "What I have tried:" section is where you need to put the code that you have tried. You also need to provide a more detailed explanation of your problem. For example, are these just random numbers to be summed or is the number going to be on the label next to the checkbox, or the checkbox caption or stored in a the control's Tag property, or ... you get the idea.

Edit: Not sure why on earth you would use nested If statements or even a Switch. Something else code from you will help clarify

Change your point of view. Each checkbox can have an event handler and, when checked, it's value is added to a storage variable. When unchecked, its value is subtracted.

The sum exists at all times, automatically. Furthermore, you can add or remove buttons as you wish without modifying any of the other code - they aren't actually aware of one another.
   
Comments
Maciej Los 1-Apr-21 8:59am
   
5ed!
Loop through the Controls array and find each checkbox - that's trivial:
C#
foreach (Control c in Controls)
   {
   if (c is CheckBox cb)
       {
       ...
       }
   }
Then your only problem is finding the relevant label though all the checkboxes I am aware of have their own Text property and don't require a separate label. If you must use a separate Label control, then I'd use the Tag property of teh CheckBox control to refer to the relevant Label and get it that way.

Then all you need to do is convert the string based number to a numeric value (I'd suggest the various TryParse methods) and add 'em.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900