C# Limit textbox to number or letter only

VAer-4038 771 Reputation points
2021-01-02T23:14:17.587+00:00

I have asked the same question before, the thread becomes messy somewhat. Now I think it is better to reorganize my question.

First, I only want the input character to be: A-Z, a-z, 0-9. there are only 62 characters allowed.

For below code, it can compile, which is good, but that is not what I want. I have tried both IF statement, both of them accept dot key. I don't want dot key.

Now here are two new questions:

  • How to exclude dot key?
  • I would like to move the code to a bool statement public static bool isTextboxOnlyNumberOrLetter(), which will be called by many textbox from multiple forms. How to write the bool statement? How to call it?

Thanks.

        private void txtUserID_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!char.IsNumber(ch) && !char.IsLetter(ch) && ch !=8 && ch != 46)  //8 is Backspace key; 46 is Delete key. This statement accepts dot key. 
            //if (!char.IsLetterOrDigit(ch) && !char.IsLetter(ch) && ch != 8 && ch != 46)   //This statement accepts dot key. 
            {
                e.Handled = true;
                MessageBox.Show("Only accept digital character or letter.");
            }

        }
Developer technologies | Visual Studio | Other
{count} votes

Accepted answer
  1. Dylan Zhu-MSFT 6,426 Reputation points
    2021-01-04T06:04:30.543+00:00

    Hi VAer,

    >How to exclude dot key?

    You need to remove the && ch != 8 && ch != 46, the IsLetterOrDigit has indicates whether a character is categorized as a letter or a decimal digit.

    >I would like to move the code to a bool statement public static bool isTextboxOnlyNumberOrLetter(), which will be called by many textbox from multiple forms. How to write the bool statement? How to call it?
    1. create a class into your project, like this:
      53074-image.png
    2. call it in the form you want:
      53086-image.png

    Best Regards,
    Dylan


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our **documentation to enable e-mail notifications if you want to receive the related email notification for this thread.**

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. David Lowndes 4,726 Reputation points
    2021-01-03T11:13:12.163+00:00

    To answer you immediate question, 46 is '.'

    0 comments No comments

  2. Wyatt C Jackson 1 Reputation point
    2021-01-24T01:03:04.647+00:00

    What you can do is check the input after it is submitted to see weither it contains any invalid characters. That would possibly be simpler and easier to implement.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.