Hi am quite new to visual studios.
This is my code so far to make an example of an atm, i have a text box and i put an amount in and then i have this button where i clic
The problem is that the value in textboxamount.Text
contains something that can't be converted to a double.
The best way to handle this is to use double.TryParse
instead:
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...
You can't trust your user to type exactly a double value in your textbox.
The Parse method cannot avoid an exception if the input cannot be converted to a double.
Instead the double.TryParse methods give the chance to test if the value typed is effectively a double. Also it seems that you are working with currency values, so perhaps it is better to use a decimal data type and when building the output string use the appropriate formatting to get a correct currency string for your locale. This will also avoid rounding errors intrinsically present in the double/single datatype
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");
}
String in textboxamount.Text
can not be parsed as double. To avoid exception you can use double.TryParse
instead.
double amount;
if(double.TryParse(textboxamount.Text, out amount))
{
totalamount += amount;
}
Also, label2
seems to be Label
and you must use
label2.Text = balance1 + totalamount;
instead.
Two major issues cause this error:
,
and .
to be flipped.Possibly including ,
but I don't remember offhand whether that is an error condition.