Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there someway I can use an array or something else to reduce the Code here?

I have 7 Radio buttons and 5 check boxes. This is the code for if the first Radio button is selected and the first checkbox is selected, along with other. This only works if the first checkbox is checked. That means I have create this all over again for each check box. Which is all for the first Radio button if that makes sense. I realize doing so would just be a big mess of code. It'd work, but it'd be very very sloppy.

So, I was wondering if there is some way i can do this in an array or something else? I just want to shorten this up A LOT. Any help with this will be greatly appreciated. Thank you.

if (radBrick.Checked)
{
    intBrick = 100000;
    intTotal = intBrick;

    if (chkBasketball.Checked)
    {
        intBasketball = 50000;
        intTotal = intBrick + intBasketball;

        if (chkFire.Checked)
        {
            intFire = 500;
            intTotal = intBrick + intBasketball + intFire;

            if (chkMarble.Checked)
            {
                intMarble = 20000;
                intTotal = intBrick + intBasketball + intFire + intMarble;

                if (chkSteel.Checked)
                {
                    intStain = 10000;
                    intTotal = intBrick + intBasketball + intFire + intStain + intMarble;

                    if (chkGarage.Checked)
                    {
                        intGarage = 5000;
                        intTotal = intBrick + intBasketball + intFire + intStain + intMarble + intGarage;
                    }
                }
            }
        }
    }

    lblTotal.Text = intTotal.ToString("C");
}
like image 637
Travis Avatar asked Feb 14 '23 11:02

Travis


2 Answers

Yes, you can - here is how:

int[] add = new[] {100000, 50000, 500, 20000, 10000, 50000};
bool[] check = new[] {radBrick.Checked, chkBasketball.Checked, chkFire.Checked, chkMarble.Checked, chkSteel.Checked, chkGarage.Checked};
int sum = 0;
for (int i = 0 ; i != add.Length ; i++) {
    if (check[i]) {
        sum += add[i];
    }
}
like image 135
Sergey Kalinichenko Avatar answered Feb 17 '23 01:02

Sergey Kalinichenko


Try transforming the Checked property into a 0 or 1 int value and multiply that times the fixed numbers and add everything up. More or less like this:

intBrick = 100000;
intBasketball = 50000;
intFire = 500;
intMarble = 20000;
intStain = 10000;
intGarage = 5000;

intTotal = (radBrick.Checked ? 1 : 0) * (intBrick +
           (chkBasketball.Checked ? 1 : 0) * (intBasketball +
           (chkFire.Checked ? 1 : 0) * (intFire +
           (chkFire.Checked ? 1 : 0) * (intMarble +
           (chkStain.Checked ? 1 : 0) * (intStain +
           (chkGarage.Checked ? 1 : 0) * intGarage)))));
like image 31
acfrancis Avatar answered Feb 16 '23 23:02

acfrancis