Only allowing up to three digit numeric characters in a text box

前端 未结 3 2054
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 00:36

Is there a way to only allow a user to input a maximum number of characters into a text box? I want the user to input a mark/grade and only be able to input 0 - 100. Below I

3条回答
  •  悲&欢浪女
    2020-12-22 01:21

    This version set textBox1.Text to empty string if fail to parse

    private void textBox1_TextChanged(object sender, EventArgs e) {
        int i;
    
        textBox1.Text=
            false==int.TryParse(textBox1.Text, out i)||0>i||i>100
                ?""
                :i.ToString();
    }
    

    If you want to keep the partial successfully parsed number then

    String previousText="";
    
    private void textBox1_TextChanged(object sender, EventArgs e) {
        var currentText=textBox1.Text;
        int i;
    
        textBox1.Text=
            int.TryParse(currentText, out i)
                ?0>i||i>99
                    ?previousText
                    :i.ToString()
                :""==currentText?currentText:previousText;
    
        previousText=textBox1.Text;
    }
    

提交回复
热议问题