Search code examples
c#visual-studiocheckboxlistgroupbox

Multiple ChechBoxes inside different GroupBoxes


I have one form that is made up of three group boxes. Two of the group boxes have two check boxes inside it and the third group box has three check boxes inside it. Each check box has an amount that will need to be calculated for a total if the box is checked.

I know I can do this with a bunch of if/else statements but am wondering if there's a simpler way for my program to loop through each group box, add up the boxes that are check, and then display a total.

If this is not the correct platform to ask this question on please just state that and I will remove this question.

Thanks in advance for any help or suggestions.


Solution

  • Assuming that you have CheckBox controls, hosted by different GroupBox controls in some Form and the Text properties of the check boxes hold digits that you want to sum. If that sounds correct, then you can achieve that through a one liner LINQ query as so:

    void SomeCaller()
    {
        var total = Controls.OfType<GroupBox>()
            .SelectMany(g => g.Controls.OfType<CheckBox>()
            .Where(c => c.Checked && int.TryParse(c.Text, out _)))
            .Sum(c => int.Parse(c.Text));
    
        txtOutput.Text = total.ToString();
    }
    

    Or ...

    void SomeCaller()
    {
        var total = new[] { groupBox1, groupBox2, groupBox3 }
            .SelectMany(g => g.Controls.OfType<CheckBox>()
            .Where(c => c.Checked && int.TryParse(c.Text, out _)))
            .Sum(c => int.Parse(c.Text));
    
        txtOutput.Text = total.ToString();
    }
    

    In case you don't prefer the LINQ way, you can do instead:

    void SomeCaller()
    {
        var total = 0;
    
        foreach (var g in Controls.OfType<GroupBox>())
            foreach (var chk in g.Controls.OfType<CheckBox>())
                if (chk.Checked && int.TryParse(chk.Text, out var value))
                    total += value;
    
        txtOutput.Text = total.ToString();
    }
    

    Use the right parsers to convert the text if you have a different data type to sum. Like decimal.TryParse(..) and decimal.Parse(..).

    ToDo:

    Create a function that sums and returns the total.