Home > Software design >  multiple checkbox selections to display in textbox
multiple checkbox selections to display in textbox

Time:09-16

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

};

CodePudding user response:

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

CodePudding user response:

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