Hi,
i need to block input if first char 2 and second char must not be more 5. And first char input must be 1 or 2. Specifically I need the input of only 1-25 and nothing else. I tried and only allow entry of numbers, but fail to limit specified :(.

One way would be to limit the keys the user can press:

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            //only allow numbers and control keys
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))  
            {
                e.Handled = true;
            }
            else if (char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                //using this rather than TextBox.Text.Length ensures
                //correct behaviour if user selects and overwrites contents of textbox
                int len = TextBox.Text.Length - TextBox.SelectionLength;

                //default to true then change to false if valid value entered
                e.Handled = true;
                switch (len)
                {

                    //allow 1 or 2 as first character
                    case 0:
                        if (e.KeyChar == '1' || e.KeyChar == '2')
                            e.Handled = false;
                        break;

                    //if this is the second character entered
                    case 1:

                        //check where user is typing. If user entered a number then moved the cursor back to start
                        //of textbox then still only allow a 1 or 2.
                        if (TextBox.SelectionStart == 0)
                        {
                            if (e.KeyChar >= '1' && e.KeyChar <= '2')
                                e.Handled = false;
                        }
                        //if the user is entering the second digit then allow 0 to 5
                        else
                        {
                            if (e.KeyChar >= '0' && e.KeyChar <= '5')
                                e.Handled = false;
                        }
                        break;

                    default:
                        break;
                }
            }
        }

This code will ensure that only numebrs from 1 to 25 can be ntered. However, there is a limitation to this solution; it will not prevent the user from PASTING invalid data into the textbox, it will only prevent them typing incorrect values.

Remember to mark the thread as solved if this has answered your question

This question has already been answered. Start a new discussion instead.