简体   繁体   English

WinForms 文本框只允许 1 到 6 之间的数字

[英]WinForms Textbox only allow numbers between 1 and 6

I want to restrict my WinForms Textbox so it only allows numbers between 1 and 6 to be entered.我想限制我的 WinForms 文本框,以便它只允许输入 1 到 6 之间的数字。 No letters, no other symbols or special characters, just those numbers.没有字母,没有其他符号或特殊字符,只有那些数字。

How do I do that?我怎么做?

You could put this on the KeyPress event of the textbox,你可以把它放在文本框的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;
  }
}

If the pressed key is (numpad) 1-6 , backspace , delete or arrowkeys allow them.如果按下的键是 (numpad) 1-6 ,则退格键、删除键或箭头键允许它们。 If it is a diffrent key don't place it and say it's handled.如果它是不同的键,请不要放置它并说它已处理。 I tested this code on a quick project it allowed me to place using the numpad 1-6 don't know of the other numbers.我在一个快速项目中测试了这段代码,它允许我使用小键盘 1-6 放置,但不知道其他数字。 If the others don't work you just have to add them as allowed and the arrow keys are not tested, but they are only needed to move left and right.如果其他人不起作用,您只需将它们添加为允许的并且不测试箭头键,但只需要左右移动即可。

Add limit: 0 to 6 and use this:添加限制: 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;
  }

The following regex should work以下正则表达式应该可以工作

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

You should be able to use it with ASP.Net Validations and WinForms您应该能够将它与 ASP.Net Validations 和 WinForms 一起使用

https://msdn.microsoft.com/en-us/library/3y21t6y4(v=vs.110).aspx 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 https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx

Keep in mind that I'm suggesting a validation after the value is submitted which may not be what you're wanting.请记住,我建议在提交值后进行验证,这可能不是您想要的。 To me, the question is ambiguous here.对我来说,这里的问题是模棱两可的。 Assuming you are using ASP.Net and you are wanting to restrict typing the values, the key press events solutions prior answers should work, but they will require at least a partial post back.假设您正在使用 ASP.Net 并且您想要限制输入值,那么先前答案的按键事件解决方案应该可以工作,但它们至少需要部分回发。 If you are want this to be handle without a post back it will require a client side script.如果您希望在没有回发的情况下处理此问题,则需要一个客户端脚本。

This is an example of how to do it client side:这是如何在客户端执行此操作的示例:

Restricting input to textbox: allowing only numbers and decimal point 限制输入到文本框:只允许数字和小数点

Since the example is for any number you will have to restrict it to the digits 1 - 6.由于该示例适用于任何数字,因此您必须将其限制为数字 1 - 6。

Here you have a simple WebForm C# with code behind on submit that will validate regex for numbers between 0-6.在这里,您有一个简单的 WebForm C#,在提交时隐藏了代码,它将验证 0-6 之间数字的正则表达式。

HTML 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>

Code behind:后面的代码:

 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
            }
        }

I would also suggest that you run RegEx validation on client side before sending request to server.我还建议您在向服务器发送请求之前在客户端运行 RegEx 验证。 That will not create any unnecessary request to server for simple validation on textbox.这不会向服务器创建任何不必要的请求,以便对文本框进行简单验证。

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

Have you tried SupressKeyPress?你试过 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;
        }

The 2nd If makes you able to press backspace if you want to change what you wrote.如果您想更改您所写的内容,则第二个 If 使您能够按退格键。

I would do something like this我会做这样的事情

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;
        }
    }

You could maybe allow use of control buttons as well eg Backspace您也可以允许使用控制按钮,例如 Backspace

Try this:尝试这个:

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;
             }
         }
     }
}

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

This WILL restrict you to 1 - 6. I have no idea how you want to use it.这会将您限制为 1 - 6。我不知道您想如何使用它。 therefore, I am simply giving you code that will provide the restriction.因此,我只是给你提供限制的代码。 this is extremely archaic, more like plebeian.这是非常古老的,更像是平民。

First, I made a form:首先,我做了一个表格:

在此处输入图片说明

Then I added the following code to the button:然后我在按钮中添加了以下代码:

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";
}

If you enter any non number the text box reads "Not a number".如果您输入任何非数字,文本框会显示“不是数字”。

1 - 6 will read "Yep, 1 - 6". 1 - 6 将读作“是的,1 - 6”。

any number < or > 1 - 6 will read " Nope, not 1 - 6".任何数字 < 或 > 1 - 6 将读作“不,不是 1 - 6”。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM