开发者

C# - Disabling Keyboard Input into a Textbox

开发者 https://www.devze.com 2023-03-20 23:55 出处:网络
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)

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" || 
             yDi开发者_Go百科splacementTextBox.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?


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


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.


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.


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


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


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.


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


This also can be used

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号