5

I have a textbox which needs only accept numbers (can be decimal values) and negative values.

Currently I have something like this in KeyPress event

   if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;                
    }

What else I should do in order to allow negative values?

Thanks

1
  • You can use regular expressions. Just use the keypress event to parse the entered text and validate it against a regular expression: ^\d+$
    – DerApe
    Oct 31, 2012 at 12:45

7 Answers 7

11
if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar)) 
        && (e.KeyChar != '.')  && (e.KeyChar != '-'))
    e.Handled = true;

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

// only allow minus sign at the beginning
if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)
    e.Handled = true;

As L.B correctly mentioned in the comments this won't allow some advanced notations like 3E-2, but for simple numbers it will do the trick.

4
  • What about this valid double 3E-2 ?
    – L.B
    Oct 31, 2012 at 12:52
  • @L.B you're right, that wouldn't work. But I didn't assume these kinds of edge cases here. Oct 31, 2012 at 12:54
  • Most europian countries use , as a decimal separator "3,5" may also be valid double for 3.5
    – L.B
    Oct 31, 2012 at 13:00
  • @DennisTraub - Is it possible to have a validation to enter only numbers and minus sign in a textbox?
    – Learner
    Jun 1, 2015 at 10:53
3

@DennisTraub's works, however there are some corner cases that it omits. For example, if the text in the textbox is "-11" and the user has the cursor at the start of the text, he or she may enter another character, such that the text could be "1-11" or ".-11". Here is an extension of his answer that seems to work for me.

TextBox textBox = sender as TextBox;
// If the text already contains a negative sign, we need to make sure that 
//    the user is not trying to enter a character at the start
// If there is already a negative sign and the negative sign is not selected, the key press is not valid
// This allows the user to highlight some of the text and replace it with a negative sign
if ((textBox.Text.IndexOf('-') > -1) && textBox.SelectionStart == 0 && !textBox.SelectedText.Contains('-'))
{
    e.Handled = true;
}
// Do not accept a character that is not included in the following
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '-')
{
    e.Handled = true;
}
// Only allow one decimal point
if ((e.KeyChar == '.') && (textBox.Text.IndexOf('.') > -1))
{
    e.Handled = true;
}            
// The negative sign can only be at the start
if ((e.KeyChar == '-'))
{
    // If the cursor is not at the start of the text, the key press is not valid
    if (textBox.SelectionStart > 0)
    {
        e.Handled = true;
    }
    // If there is already a negative sign and the negative sign is not selected, the key press is not valid
    // This allows the user to highlight some of the text and replace it with a negative sign
    if (textBox.Text.IndexOf('-') > -1 && !textBox.SelectedText.Contains('-'))
    {
        e.Handled = true;
    }
}

I have broken some stuff out that could be combined into one line. But basically you also need to check if there is already a negative sign in the text, and if the user has the cursor at the start of the text.

1

I thought that the textbox had a property where you could set the input on what is being inserted. Though I am currently not able to check this.

otherwise as an alternative you could try parsing your input to a double when submitting the value. Something like:

double myDouble;
try
{
    myDouble = double.parse(textbox.Text)
}
catch (Exception e)
{
    MessageBox.Show("Input is incorrect", "Error")
}

it's probably not the best work-around, but it might just do the trick.

1
  • 2
    I would use double.TryParse instead of getting exception for invalid values.
    – L.B
    Oct 31, 2012 at 12:55
1

Hook up the Validating event, like so:

private void myTextBox_Validating(object sender, CancelEventArgs event) {
    decimal d;
    if(!decimal.TryParse(myTextBox.Text, out d) {
        event.Cancel = true;
        //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional
        return;
    }

    if(d >= 0) {
        event.Cancel = true;
        //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional
        return;
    }
}
0
// Boolean flag used to determine when a character other than a number is entered. 
        private bool nonNumberEntered = false;

        // Handle the KeyDown event to determine the type of character entered into the control. 
        private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard. 
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad. 
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace. 
                    if(e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed. 
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number. 
            if (Control.ModifierKeys == Keys.Shift) {
                nonNumberEntered = true;
            }
        }

        // This event occurs after the KeyDown event and can be used to prevent 
        // characters from entering the control. 
        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // Check for the flag being set in the KeyDown event. 
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }
        }
0

Try this Regular Expression

"/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/" 

and use System.Text.RegularExpressions Namespace

See the example here : http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

5
  • bool b = Regex.IsMatch("33", @"/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/");
    – L.B
    Oct 31, 2012 at 13:10
  • bool b = Regex.IsMatch("33", @"^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$");
    – ravidev
    Oct 31, 2012 at 13:14
  • Now it doesn't work for 1000,000.5 (depending on the current culture it can be 1000.000,5)
    – L.B
    Oct 31, 2012 at 13:25
  • Also, has problems with negative values
    – L.B
    Oct 31, 2012 at 13:34
  • Add -? at the start of expression..Use this ^-?(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$
    – ravidev
    Nov 1, 2012 at 9:55
0

Something like:

var regex = new Regex("^[-]?\d+(\.\d+)?$", RegexOptions.Compiled);
Match m = regex.Match(textbox.Text + e.KeyChar);
e.Handled = m.Success;

Edit: It allows any real number now

5
  • What about this valid double 3E-2 ?
    – L.B
    Oct 31, 2012 at 12:54
  • @L.B though he was just talking about "numbers" eg. integers
    – DerApe
    Oct 31, 2012 at 12:57
  • From question: can be decimal values
    – L.B
    Oct 31, 2012 at 13:02
  • @derape: yes it should allow decimal values as well Oct 31, 2012 at 13:15
  • @huMptyduMpty: Well my answers only allowed decimal values, so I updated it to allow all "real" numbers: 123, -123.45, 123.45, etc
    – DerApe
    Nov 5, 2012 at 7:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.