仅允许文本框中最多三位数字字符

时间:2013-02-07 01:27:35

标签: c# textbox character numeric keystroke

有没有办法只允许用户在文本框中输入最大数量的字符?我希望用户输入标记/等级,只能输入0 - 100.下面我有监控按键的代码,只允许输入数字,但我想找到一种方法只允许用户输入最小值为0且最大值为100的数字。

private void TxtMark4_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar < '0' || e.KeyChar > '9' || e.KeyChar == ' ')
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

或者我可以使用以下内容:

if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == ' ')
{
    e.Handled = false;
}
else
{
    MessageBox.Show("You Can Only Enter A Number!");
    e.Handled = true;
}

但我想找到一种方法,只允许最多输入三个字符。

3 个答案:

答案 0 :(得分:5)

我认为它很简单:

textBox1.MaxLength = 3;

然后你处理Leave事件的最大值:

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

您还可以使用 System.Windows.Forms.NumericUpDown ,轻松设置最小值和最大值。

答案 1 :(得分:0)

如果无法解析

,此版本将textBox1.Text设置为空字符串
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();
}

如果您想保留部分成功解析的数字,那么

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

答案 2 :(得分:0)

对于每个可能的用户错误,我都会这样做。

我假设你的文本框名为TxtMark4。编写txtMark4.Content()或者你需要在if-test中读取框架中文本框的内容,它会执行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";
    }
}