[英]How Do I only accept Numeric Digits in C# Xamarin
我是Xamarin的C#新手。 我使用Visual Studio for Mac Preview在iOS应用程序上工作。 制作基本计算器时,我无法弄清楚如何不接受非数字数字的答案。 例如,在我的文本框中,如果我输入一封信,我想要一个错误
“请输入数字”。
我不知道为什么我收到错误但它不起作用。
当我运行它并输入一个数字时,它每次都默认为else语句。 还有信件。 当我在其中放入太多字母时崩溃。
partial void AddButton_TouchUpInside(UIButton sender)
{
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
int value;
string input = Console.ReadLine();
if (Int32.TryParse(input, out value))
{
number1 = double.Parse(Number1TextBox.Text);
number2 = double.Parse(Number2TextBox.Text);
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
}
我认为问题是string input = Console.ReadLine();
为什么你期望该声明具有正确的价值? 这对于控制台程序是有效的,但您正在运行iOS应用程序。
它会有意义:
string input = YourTextInput.Text;
如果要将文本输入限制为带有数字的键盘,请使用以下命令:
YourTextInput.KeyboardType = UIKeyboardType.NumberPad;
还有一件事。 如果答案应该是double
,则应该使用double.TryParse(input, out value)
而不是int。
那这个呢?
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
if (double.TryParse(Number1TextBox.Text, out number1)
&& double.TryParse(Number2TextBox.Text, out number2))
{
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
您仍然需要验证输入的数字,因为数字键盘允许输入多个小数点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.