VB.net sum values based on checkbox state

Homerboy

Lifer
Mar 1, 2000
30,890
5,001
126
There has to be an easy way to do this, but I'm just drawing a blank right now.


I have 4 NumericUpDown boxes and 4 corresponding checkboxes
and a simple formula:

Code:
Dim FC_Amount As Decimal
FC_Amount = Ck1Amount.Value + Ck2Amount.Value + Ck3Amount.Value + Ck4Amount.Value

However, I only want each value to be added into the FC_Amount if it's corresponding check box is checked.
So if only CheckBox3 is checked, then:

Code:
FC_Amount = Ck3Amount.Value

If Checkbox2 and Checkbox4 are checked, then:
Code:
FC_Amount = Ck2Amount.Value + Ck4Amount.Value


There has to be an easier way than putting in all 24 possible combinations.
 
Last edited:

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
FC_Amount = IIF(CK1.checked, val(ck1amount.value), 0) + IIF(CK2.checked, val(ck2amount.value), 0) + IIF(CK3.checked, val(ck3amount.value), 0) + IIF(CK4.checked, val(ck4amount.value), 0)



You'll need to parse the textbox's value into a numeric format, depending on what you're using to hold the sum. Val function does that, though a parse to the type of FC_Amount should be faster.
 
Last edited:

Homerboy

Lifer
Mar 1, 2000
30,890
5,001
126
FC_Amount = IIF(CK1.checked, val(ck1amount.value), 0) + IIF(CK2.checked, val(ck2amount.value), 0) + IIF(CK3.checked, val(ck3amount.value), 0) + IIF(CK4.checked, val(ck4amount.value), 0)



You'll need to parse the textbox's value into a numeric format, depending on what you're using to hold the sum. Val function does that, though a parse to the type of FC_Amount should be faster.

Deeeeeeeeeerp
Thanks. As I said I know it was obvious, just couldn't get the brain to click.

Yeah, the .values are NumericUpDowns so:

Code:
  Dim FC_Amount As Decimal

        FC_Amount = IIf(FC_1.Checked, Val(Ck1Amount.Value), 0) + IIf(FC_2.Checked, Val(Ck2Amount.Value), 0) + IIf(FC_3.Checked, Val(Ck3Amount.Value), 0) + IIf(FC_4.Checked, Val(Ck4Amount.Value), 0)
        FC_Display.Text = "Total: $" + FC_Amount.ToString("0.00")


Thanks!!!
 

Tweak155

Lifer
Sep 23, 2003
11,449
264
126
Makes more sense to create a function if you ask me (neater code), but otherwise a functional solution.