如何将一个表中的值传递给另一个表中实际更改变量默认值的变量?

时间:2017-05-10 19:26:18

标签: c# forms variables

我试图将一种形式的价值(销售税)传递给另一种形式的价值(发票总额)。我希望新值覆盖默认值。当我单步执行代码时,SalesTaxPct变量的值会更改,但是当我选择calculate时,仍会在计算中使用默认值(7.75)。任何帮助将不胜感激。

销售税表格代码:

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

发票总额表格代码:

    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();
        }
    }

1 个答案:

答案 0 :(得分:1)

如果你在btnChangePercent_Click注意到你通过声明它的类型(decimal SalesTaxPct)来创建一个新的局部变量,它是由SalesTax表单的返回正确设置的:

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 + "%)";
}

但是,类级变量SalesTaxPct已设置 NOT 。如果您删除decimal声明,它将按预期运行:

if (selectedButton == DialogResult.OK)
{
    SalesTaxPct = Convert.ToDecimal(salesTaxForm.Tag);
    lblTax.Text = "Tax(" + SalesTaxPct + "%)";
}