你对视觉工作室来说很陌生。
这是我的代码到目前为止做一个atm的例子,我有一个文本框,我把一个金额,然后我有这个按钮,我点击信用,它将金额添加到一个名为余额和我的标签还有一个名为debit的按钮,可以将钱从余额中拿走。我在wpf c#
中这样做 到目前为止,我有这个。 namespace BankAccounts
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private double totalamount = 0;
public string balance1;
private void buttoncredit_Click(object sender, RoutedEventArgs e)
{
totalamount = totalamount + double.Parse(textboxamount.Text)
balance1 = "Your Balance is: £";
label2.Content = balance1 + totalamount;
textboxamount.Clear();
}
private void buttondebit_Click(object sender, RoutedEventArgs e)
{
if (totalamount - double.Parse(textboxamount.Text) < 0)
{
MessageBox.Show("Overdraft Limit is not set please contact Customer Services");
}
else
{
totalamount = totalamount - double.Parse(textboxamount.Text);
balance1 = " Your Balance is: £";
label2.Content = balance1 + totalamount;
textboxamount.Clear();
}
}
private void listboxtransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
答案 0 :(得分:3)
textboxamount.Text
中的字符串无法解析为double。为避免异常,您可以改为使用double.TryParse
。
double amount;
if(double.TryParse(textboxamount.Text, out amount))
{
totalamount += amount;
}
此外,label2
似乎是Label
,您必须使用
label2.Text = balance1 + totalamount;
代替。
答案 1 :(得分:2)
您无法相信您的用户在文本框中输入完全双倍的值 如果输入无法转换为double,则Parse方法无法避免异常 相反,double.TryParse方法有机会测试键入的值是否实际为double。此外,您似乎正在使用货币值,因此最好使用十进制数据类型,并在构建输出字符串时使用适当的格式来为您的语言环境获取正确的货币字符串。这也将避免在double / single数据类型
中固有的舍入错误private decimal totalamount = 0;
public string balance1;
private void buttoncredit_Click(object sender, RoutedEventArgs e)
{
decimal temp;
if(decimal.TryParse(textboxamount.Text, out temp))
{
totalamount = totalamount + temp;
balance1 = "Your Balance is: ";
label2.Content = balance1 + totalamount.ToString("C");
textboxamount.Clear();
}
else
MessageBox.Show("Not a valid amount");
}
private void buttondebit_Click(object sender, RoutedEventArgs e)
{
decimal temp;
if(decimal.TryParse(textboxamount.Text, out temp))
{
if (totalamount - temp < 0)
{
MessageBox.Show("Overdraft Limit is not set please contact Customer Services");
}
else
{
totalamount = totalamount - temp;
balance1 = " Your Balance is: ";
label2.Content = balance1 + totalamount.ToString("C");
textboxamount.Clear();
}
}
else
MessageBox.Show("Not a valid amount");
}
答案 2 :(得分:1)
问题是textboxamount.Text
中的值包含无法转换为double的内容。
处理此问题的最佳方法是改为使用double.TryParse
:
private void buttoncredit_Click(object sender, RoutedEventArgs e)
{
double newAmount;
if(!double.TryParse(textboxamount.Text, out newAmount))
{
// The input is wrong - handle that
MessageBox.Show("Please enter a valid amount");
textboxamount.Focus();
return;
}
totalamount += newAmount;
balance1 = "Your Balance is: £";
label2.Content = balance1 + totalamount;
// .. Your code...
答案 3 :(得分:1)
两个主要问题导致此错误:
,
和.
被翻转。可能包括,
,但我不记得是否是错误的情况。