如何告诉我的程序它应该从数字中减去?

时间:2017-04-12 18:36:30

标签: c#

我有以下代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    double salaryAmount;
    double subtractAmount;
    double newSalaryAmount;
    string amountBackToString;

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            salaryAmount = double.Parse(TextBox1.Text);
            label1.Content = salaryAmount.ToString();
        }
        catch (Exception)
        {

            MessageBox.Show("This was not a valid input.");
        } 
    }

    private void Button2_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            subtractAmount = double.Parse(TextBox2.Text);
            newSalaryAmount = salaryAmount - subtractAmount;
            label1.Content = newSalaryAmount.ToString();
        }
        catch (Exception)
        {
            MessageBox.Show("This was not a valid input.");
        }
    }

    private void Button3_Click(object sender, RoutedEventArgs e)
    {
        amountBackToString = Convert.ToString(newSalaryAmount);
        string[] currentAmount = { amountBackToString };
        File.WriteAllLines(@"C:\Users\Silas\Downloads\Lohn.txt", currentAmount);
    }

    private void Button4_Click(object sender, RoutedEventArgs e)
    {
        string text = File.ReadAllText(@"C:\Users\Silas\Downloads\Lohn.txt");
        label1.Content = text;
        salaryAmount = Convert.ToDouble(label1.Content);
    }
}

问题是它每次都会将数字重置为初始输入然后减去,但它应该采取初始输入并继续从中减去

我的计划是薪水计算器。

enter image description here

1 个答案:

答案 0 :(得分:2)

您只需将newSalaryAmount应用于当前的salaryAmount

即可
private void Button2_Click(object sender, RoutedEventArgs e)
{
    try
    {
        subtractAmount = double.Parse(TextBox2.Text);
        newSalaryAmount = salaryAmount - subtractAmount;

        //Set the new current salary
        salaryAmount = newSalaryAmount
        label1.Content = newSalaryAmount.ToString();
    }
    catch (Exception)
    {
        MessageBox.Show("This was not a valid input.");
    }
} 

在您的情况下,salaryAmount将始终保持TextBox1.Text给出的初始值,因此当您再次减少该值时,将会采用此后没有更改的值。