How do I make a textbox that only accepts numbers?

后端 未结 30 1631
梦如初夏
梦如初夏 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:51

    Both integers and floats need to be accepted, including the negative numbers.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // Text
        string text = ((Control) sender).Text;
    
        // Is Negative Number?
        if (e.KeyChar == '-' && text.Length == 0)
        {
            e.Handled = false;
            return;
        }
    
        // Is Float Number?
        if (e.KeyChar == '.' && text.Length > 0 && !text.Contains("."))
        {
            e.Handled = false;
            return;
        }
    
        // Is Digit?
        e.Handled = (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar));
    }
    

提交回复
热议问题