简体   繁体   中英

How to set TextBox to only accept numbers?

I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;
        if ( !char.IsDigit(ch))
        {

            e.Handled = true;
        }
    }

but this is not what I wanted (I dont use physical laptop keyboard).

屏幕截图

As shown in screenshot, I have windows form with buttons and a textbox. I designed this keyboard and it works well but I want textbox1 to only accept numbers and the ".".

There are only two lines of code inside each button (and only code in the project) which is:

private void buttonName_Click(object sender, EventArgs e)
    {    
         // each button only has this code.

         textBox1.Focus();
         SendKeys.Send(buttonName.Text);  
    }

I know how to set txtbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have control buttons in windwos form and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you

Declare a string variable at form level, use it to store the last valid text and to restore it when an invalid text is entered on the TextChanged event of your textbox.

string previousText;

public Form1()
{
    InitializeComponent();
    previousText = String.Empty;
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int dummy, changeLenght, position;
    if (!String.IsNullOrWhiteSpace(textBox1.Text) && !int.TryParse(textBox1.Text, out dummy))
    {
        position = textBox1.SelectionStart;
        changeLenght = textBox1.TextLength - previousText.Length;
        textBox1.Text = previousText;
        textBox1.SelectionStart = position - changeLenght;
    }
    else
    {
        previousText = textBox1.Text;
    }
}

position and changeLenght are used to keep the cursor where it was before restoring the text.

In case you want to accept numbers with decimals or something bigger than 2147483647, just change dummy to double and use double.TryParse instead of int.TryParse .

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int changeLenght, position;
    double dummy;
    if (!String.IsNullOrWhiteSpace(textBox1.Text) && !double.TryParse(textBox1.Text, out dummy))
    {
        ...
    }
}

Suppose button1 is your button control, you could do this:

private void allButtons_Click(object sender, EventArgs e)
{  
    Button btn = sender as Button;
    char c = btn.Text[0]; //assuming all buttons have exactly 1 character
    if(Char.IsDigit(c) || c == '.')
    {
        //process
        textBox1.Focus();
        SendKeys.Send(btn.Text);
    }
    //otherwise don't
}

I'm assuming you put this in a common handler, to which you already wired all your buttons (ie allButtons_Click ).

Problem with this approach, it allows you to type values like 0.0.1 , which are most likely invalid in your context. Another way to handle this is to process TextChanged event, store previous value, and if new value is invalid, restore the old one. Unfortunately, TextBox class does not have TextChanging event, which could be a cleaner option.

The benefit of you determining the invalid value is modularity. For example, if you later decide your user can enter any value, but only numbers can pass validation, you could move your check from TextChanged to Validate button click or similar.

Why users may want that - suppose one of the options for input is copy/paste - they want to paste invalid data and edit it to become valid, for example abc123.5 . If you limit them at the entry, this value will not be there at all, so they now need to manually paste into Notepad, cut out in the invalid characters, and paste again, which goes against productivity.

Generally, before implementing any user interface limitation, read "I won't allow my user to...", think well, whether it's justified enough. More often than not, you don't need to limit the user, even for the good purpose of keeping your DB valid etc. If possible, never put a concrete wall in front of them, you just need to guide them correctly through your workflow. You want users on your side, not against you.

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