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

ぃ、小莉子 提交于 2019-11-29 17:05:14

I think it is as simple as:

textBox1.MaxLength = 3;

Then you handle the maximum value on the Leave event:

    private void textBox1_Leave(object sender, EventArgs e)
    {
        string s = (sender as TextBox).Text;
        int i = Convert.ToInt16(s);

        if (i > 100)
        {
            MessageBox.Show("Number greater than 100");
            (sender as TextBox).Focus();
        }
    }

or

You could also use System.Windows.Forms.NumericUpDown where you can easily setup minimum and maximum.

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;
}

I would do it like this with catch for every possible user error.

I'm assuming you textbox is named TxtMark4. Write txtMark4.Content() or what ever you need to read the content of the textbox in your framework in the if-test which does the TryParse

private void TxtMark4_KeyPress(object sender, KeyPressEventArgs e)
{
    int? tmp = null; //signed to allow it to be assigned the value of null
    if(int.TryParse(txtMark4.Text,out tmp)){
        if(tmp >=0 && tmp <= 100){
        //Here the number is between 0 and 100
        }
        else{//Number is below 0 or above 100
            if(tmp > 100){
                TxtMark4.Text = TxtMark4.Text.remove(2); //This will forcefully make it less or equal to 100
                DisplayLabel.text = "Numbers between 0-100 only";
            }
            else{
                TxtMark4.Text = ""; //and if its below 0 it will not be displayed
                DisplayLabel.text = "Numbers between 0-100 only";
            }
        }
    }
    else{//Not a number
        //Return some indicator to the user
        DisplayLabel.text = "numbers only";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!