Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c # creating functions and referencing objects

This time around I have to turn a previously written code in a function and call the function in the code. I am having a problem when referencing my label box and can't seem to find an answer. Here's the code:

private void btnEndSale_Click(object sender, EventArgs e)
{
    dblGrandTotal = dblSubtotal + dblTaxTotal;
    lbxTally.Items.Add("");
    lbxTally.Items.Add("");
    lbxTally.Items.Add("Subtotal: " + dblSubtotal.ToString("C"));
    lbxTally.Items.Add("Tax Total: " + dblTaxTotal.ToString("C"));
    lbxTally.Items.Add("Grand Total: " + dblGrandTotal.ToString("C"));
}

and here's what I'm trying to turn it into:

static void PurchaseTotal(ref double dblSubtotal, ref double dblTaxTotal, ref double dblGrandTotal, object lbxTally)    
{
    dblGrandTotal = dblSubtotal + dblTaxTotal;
    lbxTally.Items.Add("");
    lbxTally.Items.Add("");
    lbxTally.Items.Add("Subtotal: " + dblSubtotal.ToString("C"));
    lbxTally.Items.Add("Tax Total: " + dblTaxTotal.ToString("C"));
    lbxTally.Items.Add("Grand Total: " + dblGrandTotal.ToString("C"));
}

So that I can just use:

private void btnEndSale_Click(object sender, EventArgs e)           
{
    PurchaseTotal()
}

I'm getting a little lost as to how to reference the object label box (or if I need to?) and if I need to reference my variables again in the PurchaseTotal function when I call it. Any help is appreciated! Thanks!

like image 567
Bill Avatar asked Apr 08 '26 20:04

Bill


1 Answers

By the looks of things, all the objects you need exist as class members (e.g. they are declared within the form itself) so you can reference them from any instance method.

With that said, you should simply be able to do this:

private void btnEndSale_Click(object sender, EventArgs e)
{
    PurchaseTotal();
}

private void PurchaseTotal()
{
    dblGrandTotal = dblSubtotal + dblTaxTotal;
    lbxTally.Items.Add("");
    lbxTally.Items.Add("");
    lbxTally.Items.Add("Subtotal: " + dblSubtotal.ToString("C"));
    lbxTally.Items.Add("Tax Total: " + dblTaxTotal.ToString("C"));
    lbxTally.Items.Add("Grand Total: " + dblGrandTotal.ToString("C"));
}
like image 56
Trevor Pilley Avatar answered Apr 10 '26 09:04

Trevor Pilley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!