I am trying to pass the value in one form (Sales Tax) to a variable in another (Invoice Total). I want the new value to override the default value. When I step through the code the value of the SalesTaxPct variable changes, but then when I select calculate, the default value (7.75) is still used in the calculation. Any help would be much appreciated.
Code for Sales Tax Form:
public frmSalesTax()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
if (IsValidData())
{
this.SaveData();
}
}
private void SaveData()
{
string salesTaxPct = Convert.ToString(txtSalesTaxPct.Text);
this.Tag = salesTaxPct;
this.DialogResult = DialogResult.OK;
}
Code for Invoice Total Form:
public frmInvoiceTotal()
{
InitializeComponent();
}
//removed the constant
decimal SalesTaxPct = 7.75m;
private void btnChangePercent_Click(object sender, EventArgs e)
{
Form salesTaxForm = new frmSalesTax();
DialogResult selectedButton = salesTaxForm.ShowDialog();
if (selectedButton == DialogResult.OK)
{
decimal SalesTaxPct = Convert.ToDecimal(salesTaxForm.Tag);
lblTax.Text = "Tax(" + SalesTaxPct + "%)";
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValidData())
{
decimal productTotal = Convert.ToDecimal(txtProductTotal.Text);
decimal discountPercent = .0m;
if (productTotal < 100)
discountPercent = .0m;
else if (productTotal >= 100 && productTotal < 250)
discountPercent = .1m;
else if (productTotal >= 250)
discountPercent = .25m;
decimal discountAmount = productTotal * discountPercent;
decimal subtotal = productTotal - discountAmount;
decimal tax = subtotal * SalesTaxPct / 100;
decimal total = subtotal + tax;
txtDiscountAmount.Text = discountAmount.ToString("c");
txtSubtotal.Text = subtotal.ToString("c");
txtTax.Text = tax.ToString("c");
txtTotal.Text = total.ToString("c");
txtProductTotal.Focus();
}
}
If you will notice in btnChangePercent_Click
you create a new, local variable by declaring it's type ( decimal SalesTaxPct
) which is correctly set by the return from the SalesTax form:
if (selectedButton == DialogResult.OK)
{
// In the net line you're declaring a new, local
// variable instead of using the class level variable
decimal SalesTaxPct = Convert.ToDecimal(salesTaxForm.Tag);
lblTax.Text = "Tax(" + SalesTaxPct + "%)";
}
However, the class-level variable, SalesTaxPct
, has NOT been set. If you remove the decimal
declaration, it will work as you expect:
if (selectedButton == DialogResult.OK)
{
SalesTaxPct = Convert.ToDecimal(salesTaxForm.Tag);
lblTax.Text = "Tax(" + SalesTaxPct + "%)";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.