【问题标题】:WinForms Textbox only allow numbers between 1 and 6WinForms 文本框只允许 1 到 6 之间的数字
【发布时间】:2015-03-30 18:19:10
【问题描述】:

我想限制我的 WinForms 文本框,使其只允许输入 1 到 6 之间的数字。没有字母,没有其他符号或特殊字符,只有这些数字。

我该怎么做?

【问题讨论】:

  • wpf 或 winforms,还是...?
  • 你应该更具体。你用的是什么框架(asp.net、winforms、wpf)?
  • @T-Rex 我可以诚实地推荐的最好的事情是你先自己尝试一些东西......然后向我们展示你做了什么以及你遇到问题的地方......这不是那个困难,但你也不应该只是坐等别人给你/为你提供解决方案
  • 我使用 winforms 抱歉忘记添加了。 @MethodMan 我尝试了许多不同的解决方案,但都没有奏效。

标签: c# winforms textbox


【解决方案1】:

你可以把它放在文本框的KeyPress事件上,

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
  switch (e.KeyChar)
  {
    //allowed keys 1-6 + backspace and delete + arrowkeys
    case (char)Keys.Back:
    case (char)Keys.Delete:
    case (char)Keys.D0:
    case (char)Keys.D1:
    case (char)Keys.D2:
    case (char)Keys.D3:
    case (char)Keys.D4:
    case (char)Keys.D5:
    case (char)Keys.D6:
    case (char)Keys.Left:
    case (char)Keys.Up:
    case (char)Keys.Down:
    case (char)Keys.Right:
        break;
    default:
        e.Handled = true;
        break;
  }
}

如果按下的键是 (numpad) 1-6 ,退格键、删除键或箭头键允许它们。 如果它是一个不同的键,请不要放置它并说它已处理。我在一个快速项目上测试了这段代码,它允许我使用小键盘 1-6 放置不知道其他数字。如果其他都不起作用,您只需按允许添加它们,并且箭头键未经过测试,但只需左右移动即可。

【讨论】:

    【解决方案2】:

    你试过 SupressKeyPress 吗?

    if (e.KeyCode < Keys.D1 || e.KeyCode > Keys.D6 || e.Shift || e.Alt)
            {
                e.SuppressKeyPress = true;
            }
    
            if (e.KeyCode == Keys.Back)
            {
                e.SuppressKeyPress = false;
            }
    

    如果你想改变你写的内容,第二个 If 可以让你按退格键。

    【讨论】:

      【解决方案3】:

      以下正则表达式应该可以工作

      Regex rgx = new Regex(@"^[1-6]+$");
      rgx.IsMatch("1a23"); //Returns False
      rgx.IsMatch("1234"); //Returns True;
      

      您应该能够将它与 ASP.Net Validations 和 WinForms 一起使用

      https://msdn.microsoft.com/en-us/library/3y21t6y4(v=vs.110).aspx

      https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx

      请记住,我建议在提交值后进行验证,这可能不是您想要的。对我来说,这里的问题是模棱两可的。假设您使用的是 ASP.Net 并且您希望限制键入值,则按键事件解决方案之前的答案应该可以工作,但它们至少需要部分回发。如果您希望在没有回发的情况下处理此问题,则需要客户端脚本。

      这是一个如何在客户端执行的示例:

      Restricting input to textbox: allowing only numbers and decimal point

      由于该示例适用于任何数字,因此您必须将其限制为数字 1 - 6。

      【讨论】:

        【解决方案4】:

        这里有一个简单的 WebForm C#,在提交时包含代码,用于验证 0-6 之间数字的正则表达式。

        HTML

        <div class="jumbotron">
            <h1>ASP.NET</h1>
            <p class="lead">
                <asp:TextBox runat="server" ID="tbForValidation"></asp:TextBox>
                <asp:Button runat="server" ID="btnSubmit" Text="Validate" OnClick="btnSubmit_Click" />
            </p>
        </div>
        

        背后的代码:

         protected void btnSubmit_Click(object sender, EventArgs e)
                {
                    Regex regularExpression = new Regex(@"^[0-6]$");
        
                    if (regularExpression.IsMatch(tbForValidation.Text))
                    {
                        //Is matching 0-6
                    }
                    else
                    {
                        //Is not matching 0-6
                    }
                }
        

        我还建议您在向服务器发送请求之前在客户端运行 RegEx 验证。这不会向服务器创建任何不必要的请求以在文本框上进行简单验证。

        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid number" ValidationExpression="^[0-6]$" ControlToValidate="tbForValidation"></asp:RegularExpressionValidator>
        

        【讨论】:

        • 正则表达式 @"^[0-6]$" 将只允许您输入单个数字 0-6。正则表达式 @"^[0-6]+$" 将允许您输入 0-6 之间的许多数字。
        • 那是对的,可能是让我错过了理解的问题。如果您想添加许多数字,您的正则表达式是正确的。
        【解决方案5】:

        我会做这样的事情

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.D2 || e.KeyCode == Keys.D3 || e.KeyCode == Keys.D4 || e.KeyCode == Keys.D5 || e.KeyCode == Keys.D6)
                {
                    e.Handled = true;
                }
            }
        

        您也可以允许使用控制按钮,例如退格

        【讨论】:

          【解决方案6】:

          添加限制:06 并使用:

          private void txtField_KeyPress(object sender, KeyPressEventArgs e)
          {
              if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
                      e.Handled = true;
              if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
                  e.Handled = true;
            }
          

          【讨论】:

            【解决方案7】:

            试试这个:

            private void textBox1_TextChanged(object sender, EventArgs e)
            {
                int tester = 0;
                try
                {
                    if (textBox1.Text != null)
                    {
                        tester = Convert.ToInt32(textBox1.Text);
                        if (tester >= 30)
                        {
                            textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
                            textBox1.Select(textBox1.Text.Length, 0);
                        }
                    }
                 }
                 catch (Exception)
                 {
                     if (textBox1.Text != null)
                     {
                         try
                         {
                            if (textBox1.Text != null)
                            {
                                textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
                                textBox1.Select(textBox1.Text.Length, 0);
                            }
                         }
                         catch (Exception)
                         {
                             textBox1.Text = null;
                         }
                     }
                 }
            }
            

            【讨论】:

              【解决方案8】:

              使用正则表达式 @"^[1-6]$" 在文本框中验证此类输入。

              【讨论】:

                【解决方案9】:

                这会将您限制为 1 - 6。 我不知道你想如何使用它。 因此,我只是给你提供限制的代码。 这是非常古老的,更像是平民。

                首先,我做了一个表格:

                然后我将以下代码添加到按钮中:

                int testValue;
                // only numbers will drop into this block
                if(int.TryParse(textBox1.Text, out testValue)){
                // hard coded test for your desired values
                    if(testValue == 1 || testValue == 2 || testValue == 3 || testValue == 4 || testValue == 5 || testValue == 6){
                        // this is here just to give us proof of the return
                        textBox1.Text = "Yep, 1 - 6";
                    }
                    else{
                        // you can throw an exception here, popup a message, or populate as I did here.
                        // this is here just to give us proof of the return 
                        textBox1.Text = "Nope, not 1 - 6";
                        }
                    }
                    // you can throw an exception here, popup a message, or populate as I did here.
                else{
                    textBox1.Text = "Not a number";
                }
                

                如果您输入任何非数字,文本框会显示“非数字”。

                1 - 6 将读作“是的,1 - 6”。

                任何数字 1 - 6 都会读作“不,不是 1 - 6”。

                祝你好运!

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-10-24
                  • 2014-06-09
                  • 2020-08-18
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-04-12
                  • 1970-01-01
                  相关资源
                  最近更新 更多