3

I am trying to disable all keystrokes entered into a text box except the following:

0 1 2 3 4 5 6 7 8 9 . (so all keys except the numbers and the '.' should be disabled)

Right now I have the following code but it only checks to see if a letter was entered as the first value (not to mention its really sloppy):

    private void yDisplacementTextBox_TextChanged(object sender, EventArgs e)
    {
         if (yDisplacementTextBox.Text.ToUpper() == "A" || yDisplacementTextBox.Text.ToUpper() == "B" || yDisplacementTextBox.Text.ToUpper() == "C" ||
             yDisplacementTextBox.Text.ToUpper() == "D" || yDisplacementTextBox.Text.ToUpper() == "E" || yDisplacementTextBox.Text.ToUpper() == "F" || 
             yDisplacementTextBox.Text.ToUpper() == "G" || yDisplacementTextBox.Text.ToUpper() == "H" || yDisplacementTextBox.Text.ToUpper() == "I" ||
             yDisplacementTextBox.Text.ToUpper() == "J" || yDisplacementTextBox.Text.ToUpper() == "K" || yDisplacementTextBox.Text.ToUpper() == "L" ||
             yDisplacementTextBox.Text.ToUpper() == "M" || yDisplacementTextBox.Text.ToUpper() == "N" || yDisplacementTextBox.Text.ToUpper() == "O" ||
             yDisplacementTextBox.Text.ToUpper() == "P" || yDisplacementTextBox.Text.ToUpper() == "Q" || yDisplacementTextBox.Text.ToUpper() == "R" ||
             yDisplacementTextBox.Text.ToUpper() == "S" || yDisplacementTextBox.Text.ToUpper() == "T" || yDisplacementTextBox.Text.ToUpper() == "U" ||
             yDisplacementTextBox.Text.ToUpper() == "V" || yDisplacementTextBox.Text.ToUpper() == "W" || yDisplacementTextBox.Text.ToUpper() == "X" ||
             yDisplacementTextBox.Text.ToUpper() == "Y" || yDisplacementTextBox.Text.ToUpper() == "Z")
        {
            MessageBox.Show("Please enter a numeric value for the Y Displacement.", "Y Displacement: Numbers Only Error",
                       MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }

Is there anyway to have it so when pressed, all of the keys on the keyboard (except the numbers and the period button) do not register (or disables) the actual value of the key and inputs nothing?

4
  • as a first suggestion, your logic would be much simpler to look for the letters you DO want to allow, and ignoring (or prompting) anything that isn't 0-9 or .. Commented Jul 18, 2011 at 23:29
  • Have a look at this post. Hope it helps. Commented Jul 18, 2011 at 23:30
  • Is this winforms or wpf? You should remove the input tag, and add one of those tags. Commented Jul 18, 2011 at 23:32
  • @Merlyn: WinForms using VS2010 Commented Jul 19, 2011 at 16:19

9 Answers 9

6

Use textBox1.KeyPress += textBox1_KeyPress

This code only allowing numbers and . and the backspace.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
    { 
        e.Handled = true; 
    }
    //Edit: Alternative
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
    {
        e.Handled = true;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Char.IsNumber() can be useful here
@Rubens: you are right, I add to answer as alternative, thanks.
this method allows Enter
1

There are two ways you could try to approach this:

  1. Wait for the user to finish entering the data, then use double.TryParse() to make sure it's a valid number.

  2. Use the KeyPress event of the TextBox to validate the data as each key is pressed.

Comments

0

Take a look here: Simple Numeric TextBox

EDIT: As other answers explains what to do dealing with OnKeyPress/OnKeyDown events, this article demonstrates how to deal with other scenarios, as pasting text, so I'll keep this answer.

Comments

0

You should hook into the KeyDown and KeyPress event to prevent the input of unwanted characters. There is a sample on MSDN

Comments

0

Many third party control libraries also have this kind of functionality built in if you ever find yourself using one of them.

Comments

0

It is better practice to allow typing anything but give notification through an error provider about the failing validation (Validating event and double.TryParse()).

But if you insist, be sure to replace the '.' with the decimal separator of the system. If you are not assuming all values to be English you can easily get into a cannot-enter-a-decimal-value problem.

For instance, I am in Croatia and here we have to type a comma (,). In some islamic country I fail to remember the decimal separator is a hash (#).

So beware of localization issues.

Comments

0

The below code will suppress all but number, the backspace, and the decimal. It also only allows a single decimal for numeric entry.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
    { 
        e.Handled = true;
        return; 
    }
    if(e.KeyChar == '.' && textBox1.Text.Contains('.'))
    {
        e.Handled = true;
    }
}

Comments

0

This also can be used

if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.'){
            e.Handled = true;}

Comments

0

Shortest fix to make text/cmb box read-only, attach following to respective keypress event :

private void cmbDisable_KeyPress(object sender, KeyPressEventArgs e) { e.KeyChar = (char)(0); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.