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.
这篇关于在文本框中只允许最多三位数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在文本框中只允许最多三位数字字符
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01