Restricting users to input only numbers in C# windows application

后端 未结 6 703
小鲜肉
小鲜肉 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: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;
        }
    

提交回复
热议问题