LJay
LJay

Reputation: 11

Multiple checkbox selections to display in textbox

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";
}

Upvotes: 0

Views: 997

Answers (2)

Lars Kristensen
Lars Kristensen

Reputation: 1495

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");
}

Upvotes: 1

Niel
Niel

Reputation: 96

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
    }
}

Upvotes: 1

Related Questions