2017-05-10 3 views
0

하나의 양식 (판매 세)에서 다른 값 (송장 합계)의 값으로 값을 전달하려고합니다. 새 값을 기본값보다 우선 적용하겠습니다. 코드를 단계별로 실행하면 SalesTaxPct 변수의 값이 변경되지만 계산을 선택하면 기본값 (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; 
    } 

코드 송장의 총 양식 : 당신이 btnChangePercent_Click에 알 수있는 경우

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

이 줄의 시작 부분에서'decimal'을 제거하려고 :'진수 SalesTaxPct = Convert.ToDecimal (salesTaxForm.Tag) ':이처럼 보인다 기존 변수를 수정하는 대신 새 변수를 선언하고 있습니다. – WhiteRuski

답변

1

당신이 그것을 유형의 선언에 의해 새로운 지역 변수를 생성 (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이 아니며이 설정되었습니다. 당신이 decimal 선언을 제거 할 경우, 당신이 예상대로 작동합니다

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