Restricting users to input only numbers in C# windows application

后端 未结 6 661
小鲜肉
小鲜肉 2020-12-30 11:19

I have tried this code to restrict only numbers.It type only numbers and don\'t make entry when we try to enter characters or any other controls, even it doesnt enter backsp

相关标签:
6条回答
  • 2020-12-30 12:00

    you can use Char.IsDigit() method

    0 讨论(0)
  • 2020-12-30 12:06

    Use the Char.IsDigit Method (String, Int32) method and check out the NumericTextbox by Microsoft

    MSDN How to: Create a Numeric Text Box

    0 讨论(0)
  • 2020-12-30 12:10

    put following code in keypress event of your textbox:

         private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }
    
    0 讨论(0)
  • 2020-12-30 12:16

    To allow only numbers in a textbox in a windows application, use

    private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
              e.Handled = true;
    }
    

    This sample code will allow entering numbers and backspace to delete previous entered text.

    0 讨论(0)
  • 2020-12-30 12:17

    You do not need to use a RegEx in order to test for digits:

    private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (!Char.IsDigit(e.KeyChar))
              e.Handled = true;
    }
    

    To allow for backspace:

    private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
              e.Handled = true;
    }
    

    If you want to add other allowable keys, look at the Keys enumeration and use the approach above.

    0 讨论(0)
  • 2020-12-30 12:23

    Methods Suggested above only prevent user typing anything but number, but it will fail if user copy and paste some text inside textbox so we also need to check the input on text change event

    Create ontextchangeEvent

     private void TxtBox1_textChanged(object sender, EventArgs e)
        {
            if (!IsDigitsOnly(contactText.Text))
            {
                contactText.Text = string.Empty;
            }
        }
    
    private bool IsDigitsOnly(string str)
        {
            foreach (char c in str)
            {
                if (c < '0' || c > '9')
                    return false;
            }
    
            return true;
        }
    
    0 讨论(0)
提交回复
热议问题