How do I make a textbox that only accepts numbers?

后端 未结 30 1576
梦如初夏
梦如初夏 2020-11-21 06:05

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I\'ve done this kind of validation by overloading the KeyPress event

相关标签:
30条回答
  • 2020-11-21 06:40

    simply use this code in textbox :

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
    
        double parsedValue;
    
        if (!double.TryParse(textBox1.Text, out parsedValue))
        {
            textBox1.Text = "";
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:40

    This is my aproach:

    1. using linq (easy to modify filter)
    2. copy/paste proof code
    3. keeps caret position when you press a forbidden character
    4. accepts left zeroes
    5. and any size numbers

      private void numeroCuenta_TextChanged(object sender, EventArgs e)
      {
          string org = numeroCuenta.Text;
          string formated = string.Concat(org.Where(c => (c >= '0' && c <= '9')));
          if (formated != org)
          {
              int s = numeroCuenta.SelectionStart;
              if (s > 0 && formated.Length > s && org[s - 1] != formated[s - 1]) s--;
              numeroCuenta.Text = formated;
              numeroCuenta.SelectionStart = s;
          }
      }
      
    0 讨论(0)
  • 2020-11-21 06:44

    Two options:

    1. Use a NumericUpDown instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.

    2. Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox:

      private void textBox1_KeyPress(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;
          }
      }
      

    You can remove the check for '.' (and the subsequent check for more than one '.') if your TextBox shouldn't allow decimal places. You could also add a check for '-' if your TextBox should allow negative values.

    If you want to limit the user for number of digit, use: textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits

    0 讨论(0)
  • 2020-11-21 06:46

    I was also looking for the best way to check only numbers in textbox and problem with keypress was it does not support copy paste by right click or clipboard so came up with this code which validates the when cursor leaves the text field and also it checks for empty field. (adapted version of newguy)

    private void txtFirstValue_MouseLeave(object sender, EventArgs e)
    {
        int num;
        bool isNum = int.TryParse(txtFirstValue.Text.Trim(), out num);
    
        if (!isNum && txtFirstValue.Text != String.Empty)
        {
            MessageBox.Show("The First Value You Entered Is Not a Number, Please Try Again", "Invalid Value Detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtFirstValue.Clear();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:46

    In button click you can check text of textbox by for loop:

    char[] c = txtGetCustomerId.Text.ToCharArray();
    bool IsDigi = true;
    
    for (int i = 0; i < c.Length; i++)
         {
           if (c[i] < '0' || c[i] > '9')
          { IsDigi = false; }
         }
     if (IsDigi)
        { 
         // do something
        }
    
    0 讨论(0)
  • 2020-11-21 06:48

    3 solution

    1)

    //Add to the textbox's KeyPress event
    //using Regex for number only textBox
    
    private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
    e.Handled = true;
    }
    

    2) an another solution from msdn

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

    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (nonNumberEntered == true)
        {
           MessageBox.Show("Please enter number only..."); 
           e.Handled = true;
        }
    }
    

    source http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

    3) using the MaskedTextBox: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

    0 讨论(0)
提交回复
热议问题