简体   繁体   中英

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. 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,

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. 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. 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:

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

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

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

Here you have a simple WebForm C# with code behind on submit that will validate regex for numbers between 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>

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. 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?

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.

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

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. 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".

any number < or > 1 - 6 will read " Nope, not 1 - 6".

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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