How do I make a textbox that only accepts numbers?

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

    Do not forget that a user can paste an invalid text in a TextBox.

    If you want to restrict that, follow the below code:

    private void ultraTextEditor1_TextChanged(object sender, EventArgs e)
    {
        string append="";
        foreach (char c in ultraTextEditor1.Text)
        {
            if ((!Char.IsNumber(c)) && (c != Convert.ToChar(Keys.Back)))
            {
    
            }
            else
            {
                append += c;
            }
        }
    
        ultraTextEditor1.Text = append;
    }   
    

提交回复
热议问题