[英]C# Converting String to Int from textbox
我正在尝试将文本框中的字符串转换为 int,但我发现的每个 googled 答案似乎仍然带回相同的错误;
System.FormatException: '输入字符串的格式不正确。'
我的代码很简单:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
int age = Int32.Parse(txtAge.Text);
if (string.IsNullOrWhiteSpace(txtAge.Text))
{
txtAge.Clear();
MessageBox.Show("Age cannot be blank");
}
else if(age < 0 || age > 100)
{
txtAge.Clear();
MessageBox.Show("Age must be within rage 0-100");
}
}
任何帮助都将不胜感激,因为我觉得这是一个简单的错误需要解决,但我已经看了好几个小时了,现在一直在兜圈子
我希望看到更多类似的东西:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
int age;
if (Int32.TryParse(txtAge.Text, out age))
{
if (age >= 0 && age <= 100)
{
// ... do something with "age" in here ...
}
else
{
MessageBox.Show("Age must be within range 0-100");
}
}
else
{
MessageBox.Show("Invalid Age. Please enter a valid Age.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.