【问题标题】:Validate number input on text boxes [closed]验证文本框上的数字输入[关闭]
【发布时间】:2013-11-07 14:41:23
【问题描述】:

我想在 Windows 窗体应用程序的文本框中验证输入,即如果输入的数字小于 1 或大于 24 或输入除整数之外的任何其他字符,则显示错误消息框。我该怎么做呢?

【问题讨论】:

标签: c# winforms


【解决方案1】:

我会考虑这样的事情:

    //make sure that we have a valid number in the text box with no other characters       
    //loop through the string, examining each character
    for (int i = 0; i < txtHour.Text.Length; i++)
    {
        //if this character isn't a number, then don't close the form or continue           
        if (!char.IsNumber(txtHour.Text[i]))
        {
            MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
            return;
        }
    }
    //now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24
    int testInt = Convert.ToInt32(txtHour.Text);
    if (testInt < 1 || testInt > 24)
    {
        MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
        return;
    }

对于您在评论中要求的方法示例,您可以执行以下操作:

    //////////////////////////////////////////////////////////////////////
    //in your main code:
    if (!isValidHour(textBox1.Text))
        MessageBox.Show("Value for field must be a number from 1 to 24");

    if (!isValidHour(textBox2.Text))
        MessageBox.Show("Value for field must be a number from 1 to 24");

    //////////////////////////////////////////////////////////////////////

    ///method to validate if text field is an INT from 1 to 24  
    bool isValidHour (string stringToValidate)
    {
        //make sure that we have a valid number in the text box with no other characters       
        //loop through the string, examining each character
        for (int i = 0; i < stringToValidate.Length; i++)
        {
            //if this character isn't a number, then don't close the form or continue           
            if (!char.IsNumber(stringToValidate[i]))
            {
                //MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
                return false;
            }
        }
        //now that we know we have a valid number, convert the string to int and make sure it's not less than 1 or greater than 24
        int testInt = Convert.ToInt32(stringToValidate);
        if (testInt < 1 || testInt > 24)
        {
            //MessageBox.Show("Value for 'txtHour' must be a number from 1 to 24");
            return false;
        }

        return true;
    }

【讨论】:

  • 谢谢,这很好用。要扩展它以验证 2-3 个文本框的输入,是否会使用相同的代码块但更改文本框名称并创建一个新的 int,或者是否有一种方法可以验证多个文本框的输入与上面完全相同,但在一个代码块中?
  • @user2929108 - 请参阅新代码块以获取此问题的一个可能答案
  • int testInt = Convert.ToInt32(stringToValidate); 行抛出 FormatException 错误
  • @user2929108 - 我无法重现您的问题,也没有您可以评论的代码。我可以在上面编写的代码块中找到的唯一问题是,如果文本框中的数字超过 32 位,Convert.ToInt32 将出现溢出异常,但您可以轻松地添加一个 try 块或字符计数以防止这种情况。如果您不显示任何自己的代码,这里没有人能够告诉您为什么会收到 FormatException。出于这个原因,您的问题已经被搁置并标记为离题(理所当然)。
【解决方案2】:

您可以添加一个私有方法,并通过传递需要验证的文本框控件在必要时调用它。

 private void ValidateText(TextBox textbox)
        {
            int value;

            bool isConverted = Int32.TryParse(textbox.Text.Trim(), out value);
            if (!isConverted)
            {
                MessageBox.Show("Only numbers allowed");
                return;
            }

            if (value < 1 || value > 24)
            {
                MessageBox.Show("Please enter a value between 1-24");
            }
        }

Validating txtHour by invoking above method

ValidateText(txtHour);

【讨论】:

    【解决方案3】:
    try{
      if((int)item.value >= 1 && (int)item.value <=25){
        //match.
      }else{
        //error.
      }
    }catch (Exception e){
      //type error
    }
    
    //or---
    
    var itemValue = default(int);
    if(int.TryParse(item.value, out itemValue)){
      if(itemValue >= 1 && itemValue <= 25){
        //match.
      }else{
        //error.
      }
    }else{
      //item.value is not numeric.
    }
    

    【讨论】:

    • 你应该在这里使用int.Parse还是更好的int.TryParse?这里catch块是什么意思?
    • 我把它放进去是为了试图解析一些非数字的东西。如果 catch 执行,则意味着输入不是数字。如果您不想使用 catch,try 解析就足以做同样的事情。它会检查是否可以将其解析为数字。
    • TryParse 有第二个参数,标记为out。您不需要多次解析item.value。如果值不是数字,也会显示错误。
    • 嗨。感谢您的回复,尽管我不确定如何将代码适合我的程序。我想应用这个的文本框叫做txtHour
    • 我什至不会尝试第一个示例,因为 item.value 很可能是一个字符串,甚至不会强制转换。
    【解决方案4】:

    这是一个非常简单的实现,但是,这将实现您要求的验证:

    int hoursEntered;
    bool isInteger;
    isInteger = int.TryParse(txtHour.Text, out hoursEntered);
    
    if (hoursEntered < 1 || hoursEntered > 24 && isInteger == true)
       MessageBox.Show("Your number is either less than 1, greater than 24 or you didn't enter a number", "Warning!", MessageBoxButtons.OK);  
    

    这里有一些事情需要考虑。我编写了这段代码并将其绑定到事件处理程序以进行按钮单击。如果这不是您的实现,那么我会强烈考虑使用 OnKeyPress/OnKeyUp/OneKeyDown 事件来进行验证。否则,您可以将此代码复制到您已经拥有的任何按钮单击事件处理程序中。

    【讨论】:

    • 输入“2a”将解析为 2...根据操作仍然会失败。
    • @ChrisLively - 你是 100% 正确的。不幸的是,我在发布答案时被要求参加最后一分钟的会议,但没有完成。 Dizzy.stackoverflow 已经发布了我正在努力的答案。
    【解决方案5】:

    考虑使用 OnKeyPress/OnKeyDown/OnKeyUp 事件进行检查:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      相关资源
      最近更新 更多