How do I make a textbox that only accepts numbers?

后端 未结 30 1641
梦如初夏
梦如初夏 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: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();
        }
    }
    

提交回复
热议问题