检查文本框中的负输入

时间:2020-09-08 00:34:54

标签: c# winforms validation input

我正在尝试验证Windows窗体应用程序中的文本框。文本框可以使用任何数字(应该是十进制,但也可以接受整数)。我不希望该数字为负数,但是即使添加了if语句后,即使输入的数字为负数,应用程序仍然会接受它。我不确定自己在做什么错。

grr

我也尝试过

var scrollContent = $("#content").offset().top;
var scrollHero = $("#hero").offset().top;

var scrollPos = $(document).scrollTop();

if (scrollPos > scrollContent) {
    $(".image-test").css({
        "background-image": "url('')"
    });
}  else if(scrollPos < scrollContent) {
    $(".image-test").css({
        "background-image": "url('')"
    });

我发现张贴了一个类似的问题,但是它使用的语言是我尚未学习的语言,但是由于它仍然询问相同的问题,因此我尝试了张贴的一些答案,但仍然遇到问题。 链接:How do you check if an input is a negative number in VB

注意:我只想使用try catch语句来完成此操作。

2 个答案:

答案 0 :(得分:1)

我认为,验证您的输入为数字和小数的最佳方法是使用类似以下的代码。作为评论者,@ MickyD建议Decimal.TryParse像这样:

try
{
    //Different operations being done here that use the input from txtEnterTotal.Text 
}
catch(Exception ex)
{
    // catch the exception and DO something with it.
    System.Diagnostics.Trace.TraceError("Error before try/parse: {0}", ex);
    //decimal entertotal = Convert.ToDecimal(txtEnterTotal.Text);
    // old code ^^^^^^
    // new code 
    if (decimal.TryParse(txtEnterTotal.Text, out decimal entertotal))
    {
        if (entertotal <= decimal.Zero)
        {
            MessageBox.Show("Please enter a valid number for the total field.", "Entry Error");
        }
    } 
    else 
    {
        MessageBox.Show(string.Format("Failed to parse value: {0}", txtEnterTotal.Text));
    }
}

答案 1 :(得分:0)

示例代码的一个问题是您正在Convert.ToDecimal(txtEnterTotal.Text)块中执行catch,但是如果txtEnterTotal.Text不是有效数字,则会抛出异常,因此现在将无法处理异常。

由于您说过您确实要使用try/catch来验证文本框,因此基本模式是尝试转换try块中的数字,如果失败,请采取措施(不会引发其他异常)。

例如:

private void btnValidate_Click(object sender, EventArgs e)
{
    try
    {
        // Here we perform the operation that might throw an exception
        decimal value = Convert.ToDecimal(txtEnterSubtotal.Text);

        // If we get here, no exception was thrown
        MessageBox.Show("Thank you");
    }
    catch
    {
        // Since there was an exception, show a message and clear the textbox
        MessageBox.Show("Please enter a valid, positive number");
        txtEnterSubtotal.Clear();
        txtEnterSubtotal.Focus();
    }
}

但是,使用try/catch进行简单的错误处理(捕获调用栈会产生成本)是“昂贵的”,这也不是其预期的目的(它们应用于 exception 事件,无法控制正常的程序流程。

这是学习数字类型具有的TryParse方法的好时机。此方法需要一个string进行解析,如果成功,它将数字类型的一个out参数设置为转换后的值。最好的部分是它返回表示成功的bool,因此我们可以在if条件下使用它,并在字符串解析失败时采取一些措施。

例如,您可以在验证方法中使用此代码,而不再需要try/catch,因为我们改为使用TryParse进行验证:

private void btnValidate_Click(object sender, EventArgs e)
{
    // Here we check if `TryParse` does NOT return true (note the exclamation mark), OR
    // if the converted number less than zero, where in either case we take some action
    if (!decimal.TryParse(txtEnterSubtotal.Text, out decimal value) ||
        value < 0)
    {
        // Show a message, then clear the textbox
        MessageBox.Show("Please enter a valid, positive number");
        txtEnterSubtotal.Clear();
        txtEnterSubtotal.Focus();
    }
    else
    {
        MessageBox.Show("Thank you");
    }
}