I am trying to write a graphical calculator, So far the calculator works, but I want to use the Key "Enter" for it to perform the operation and give the answer. For now it just crashes whenever I press Enter
. This is the XAML code:
<TextBox Height="38" TextWrapping="Wrap" VerticalAlignment="Top"
Margin="16,23,0,0" HorizontalAlignment="Left" Width="226"
FontSize="20" Background="Black" BorderThickness="2" Name="tb"
Text="" KeyUp="KeyDownHandler">
Here is the code that handles the Enter
key event.
private void KeyDownHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
result();
}
}
private void result()
{
String op;
int iOp = 0;
if (tb.Text.Contains("+"))
{
iOp = tb.Text.IndexOf("+");
}
else if (tb.Text.Contains("-"))
{
iOp = tb.Text.IndexOf("-");
}
else if (tb.Text.Contains("*"))
{
iOp = tb.Text.IndexOf("*");
}
else if (tb.Text.Contains("/"))
{
iOp = tb.Text.IndexOf("/");
}
else
{
//error
}
op = tb.Text.Substring(iOp, 1);
double num1 = Convert.ToDouble(tb.Text.Substring(0, iOp));
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 2));
if (op == "+")
{
tb.Text = Convert.ToString(num1 + num2);
}
else if (op == "-")
{
tb.Text = Convert.ToString(num1 - num2);
}
else if (op == "*")
{
tb.Text = Convert.ToString(num1 * num2);
}
else if (op == "/")
{
tb.Text = Convert.ToString(num1 / num2);
}
}
I am beginner in C#, XAML and Visual Studio. Is this the right way of handling the Enter.key event?
This is the exception thrown:
Exception thrown: 'System.FormatException' in mscorlib.ni.dll
Change this:
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 2));
To this:
double num2 = Convert.ToDouble(tb.Text.Substring(iOp + 1, tb.Text.Length - iOp - 1));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.