嗨,我是视觉工作室的新手。
这是我的代码,到目前为止,我有一个自动取款机的例子,我有一个文本框,我放了一个金额,然后我有一个按钮,我点击信贷,它把金额添加到一个名为余额的标签上,我还有一个名为借方的按钮,它把钱从余额中拿走。我是用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)
{
}
}
}
发布于 2013-10-04 23:10:37
您不能信任您的用户在文本框中准确地键入一个双值。
如果不能将输入转换为double,则Parse方法无法避免异常。
相反,double.TryParse方法提供了测试类型值是否有效为双倍的机会。此外,您似乎正在使用货币值,所以最好使用十进制数据类型,并且在构建输出字符串时,使用适当的格式为您的区域设置获取正确的货币字符串。这还将避免双/单个数据类型本质上存在的舍入错误。
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");
}
发布于 2013-10-04 23:08:27
textboxamount.Text
中的字符串不能解析为double。为了避免异常,可以使用double.TryParse
。
double amount;
if(double.TryParse(textboxamount.Text, out amount))
{
totalamount += amount;
}
而且,label2
似乎是Label
,您必须使用
label2.Text = balance1 + totalamount;
而不是。
发布于 2013-10-04 23:08:13
问题是,textboxamount.Text
中的值包含一些不能转换为双值的内容。
处理此问题的最佳方法是使用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...
https://stackoverflow.com/questions/19192039
复制相似问题