在 C# 中的提示计算器中验证数据



我正在尝试到达当您不在框中输入数字或字母时,您会得到一个弹出框,上面写着请输入您的号码。

//converted a textbox into a decimal
Decimal enterNumber = Convert.ToDecimal(txtUserInput.Text);
// as well as vaidate the data
if (enterNumber<=0) {
MessageBox.Show("Please enter your number");
}

好的,当我尝试tryParse时,我在返回类型上出现错误,不确定返回关键字后面不能跟什么对象意味着什么

decimal filler = 0m;

if (Decimal.TryParse(txtUserInput.Text, out filler))
{
//error
return true;

}
// needs an else statment 
else {
MessageBox.Show("needs to be a number");
txtUserInput.Focus();
//error 
return false;
}

我认为标准方法是只使用货币的重载decimal.TryParse。通过这种方式,您可以在所需的区域性中检查有效的货币输入

将数字的字符串表示形式转换为其小数 等效使用指定的样式和特定于区域性的格式。一个 返回值指示转换是成功还是失败。

public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out decimal result
)

参数

  • sType: System.String要转换的数字的字符串表示形式。
  • styleType: System.Globalization.NumberStyles枚举值的按位组合,指示允许的 s 格式。要指定的典型值是"数字"。
  • 提供程序Type: System.IFormatProvider一个对象,它提供有关 s 的区域性特定分析信息。
  • resultType: System.Decimal此方法返回时,如果转换成功,则包含与 s 中包含的数值等效的十进制数,如果转换失败,则为零。如果 s 参数为 null 或 String.Empty,格式不符合样式,或者表示小于 MinValue 或大于 MaxValue 的数字,则转换将失败。此参数以未初始化的方式传递;结果中最初提供的任何值都将被覆盖。
  • 如果 s 转换成功,则返回值Type: System.Booleantrue;否则返回值为 false。

示例

// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Decimal.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);

您还可以使用 try-catch 语句来查找正确的输入类型,并且简单并完成工作

最新更新