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

Only allowing up to three digit numeric characters in a text box(在文本框中只允许最多三位数字字符)

本文介绍了在文本框中只允许最多三位数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 have code that monitors the keystroke and only allows for numbers to be input, but I want to find a way to only allow the user to input a number with a minimum value of 0 and a maximum of 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;
    }
}

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

or I could use the following:

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

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

But I would like to find a way to only allow three characters to be input maximum.

推荐答案

我觉得很简单:

textBox1.MaxLength = 3;

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

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

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

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

这篇关于在文本框中只允许最多三位数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在文本框中只允许最多三位数字字符

基础教程推荐