Search code examples
c#textboxkeypress

How to set a textbox to allow only numbers, one (1) comma, AND a dash (for negative numbers) at the beginning


This is one is a different box than the usual "i want only numbers in a textBox"

I came across with the need to use negative numbers, and I'd rather take them in a text box.

So far we can easily set decimals using the following code

  private void textBox_KeyPress_1(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
          (e.KeyChar != ','))
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
        {
            e.Handled = true;
        }
    }

And hooking it on the desired boxes in the designer this.textBoxXX.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_KeyPress_1);

So far so good, but, what if i need to add a "-" and allow it only in the beginning of the code? any hint?


Solution

  • You can try regular expressions like

    ^[0-9]([.,][0-9]{1,3})?$
    

    or

    ^-?\d*\.?\d*
    

    Here is an example of validation method

    private void ValidateText(object sender, EventArgs e)
    {
        TextBox txtBox = sender as TextBox;
        String strpattern = @"^-?\d*\.?\d*"; //Pattern is Ok
        Regex regex = new Regex(strpattern);
        if (!regex.Match(txtBox.Text).Success)
        {
            // passed
        }
    }