0

I'm new to this, please bare with... I have 4 checkboxes, each displaying a $ amount depending on the selection. I have it working so that if 1 checkbox is selected, textbox shows $1.00 or $20.00. But, I'm having trouble with if 2 checkboxes are selected it would be $21.00 or 3 checkboxes or all 4.

I have this to show one checkbox selection.

if (checkBox247Access.Checked)
{
    textBoxExtras.Text = "$1.00";
}
1
  • 1
    You could take the container all the four checkboxes are in and find the checkboxes with the Children collection. That gives you an array of checkboxes that you can iterate over (or use linq) to calculate the sum. Then assign this sum to the textbox. Commented Sep 15, 2021 at 11:31

2 Answers 2

1

something like this should work, but as in comment above you might want to use particular container to iterate through i.e. iterate through groupbox instead of entire form just incase you have checkboxes in other container/groupboxes

foreach (Control ctrl in form1.Controls)
{
    if (ctrl is CheckBox)
    {
         //do the logic of if checkbox is checked
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

One thing you can do, is handle the CheckedChanged event for all 4 checkboxes. You can even use the same eventhandler for all 4.

Then, in the handler, add up alle the selected extra options, and add them to a variable. After figuring out the total amount, update the textbox.

Here's an example:

private void checkBox_CheckedChanged(object sender, EventArgs e)
{
    int amount = 0;

    if (checkBox247Access.Checked)
    {
        amount += 20;
    }

    if (checkBoxFreeCoffee.Checked)
    {
        amount += 1;
    }

    if (checkBoxExtraThing.Checked)
    {
        amount += 3;
    }

    if (checkBoxBonusThing.Checked)
    {
        amount += 11;
    }

    textBoxExtras.Text = "$" + amount.ToString("n2");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.