我有以下代码:
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);
}
}
问题是它每次都会将数字重置为初始输入然后减去,但它应该采取初始输入并继续从中减去
我的计划是薪水计算器。
答案 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
给出的初始值,因此当您再次减少该值时,将会采用此后没有更改的值。