【发布时间】:2020-12-26 08:31:13
【问题描述】:
我正在尝试验证 Windows 窗体应用程序中的文本框。文本框接受任何数字(它应该是小数,但也接受整数)。我不希望该数字为负数,但即使在添加 if 语句之后,即使输入的数字是否定的,应用程序仍然接受它。我不确定我做错了什么。
try
{
//Different operations being done here that use the input from txtEnterTotal.Text
}
catch
{
decimal entertotal = Convert.ToDecimal(txtEnterTotal.Text);
if (entertotal <= 0)
{
MessageBox.Show("Please enter a valid number for the total field.", "Entry Error");
}
}
我也试过了
catch
{
if (decimal.TryParse(txtEnterSubtotal.Text, out decimal value))
{
if (value < 0)
{
MessageBox.Show("Please enter a valid number for the Subtotal field.", "Entry Error");
}
else
{
MessageBox.Show("thank you");
}
}
}
我发现发布了一个类似的问题,但它使用的是我尚未学过的另一种语言,但由于它仍然询问相同的问题,我尝试了一些发布的答案,但我仍然遇到问题。 链接:How do you check if an input is a negative number in VB
注意:我只想使用 try catch 语句来执行此操作。
【问题讨论】:
-
考虑使用
Decimal.TryParse()而不是try-catch。后者通常不应用于正常的程序流程。此外,Convert.ToDecimal可以反过来抛出异常,而xxx.TryParse()则不会 -
您只检查负数如果有异常 - 也就是说,在
try/catch语句的catch代码块中 - 可能没有异常,取决于try代码块中发生的情况。一般来说,您根本不需要try/catch- 请参阅@MickyD 在先前评论中的建议。 -
该链接中的代码有什么问题,它使用 .Net 方法。在 C# 中,您具有可以内联输出变量的优势:例如
if (decimal.TryParse(txtEnterTotal.Text, out decimal value)) { if (value < 0) { /* Negative value */ } } else { /* Not a valid value */ } -
我更新了我的代码并尝试过,但我的应用程序仍然接受它并进行所有计算,尽管@Jimi 是负数
-
Convert.ToDecimal(txtEnterTotal.Text)将在txtEnterTotal.Text不是有效数字时抛出异常。可能不希望在您的catch块中...
标签: c# winforms validation input