如何创建仅接受某些整数值的文本框? [英] How can I create a Textbox which only accepts certain integer values?

查看:23
本文介绍了如何创建仅接受某些整数值的文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索过,但找不到我要找的东西.我正在使用 VS2010 并尝试制作一个 w7p 应用程序.我正在尝试制作一个仅接受 0 到 5 之间的单个整数值的文本框,因此没有负数也没有小数,因为任何更高的值都会使应用程序崩溃.谢谢!

I've searched the web and was unable to find what I am looking for. I'm using VS2010 and trying to make a w7p app. I'm trying to make a textbox that only accepts a single integer value from 0 to 5, so no negative and no decimal as any value higher crashes the app. Thank you!

推荐答案

使用 NumericUpDown 控件,如果有的话你可以只设置 Minimum>最大属性.

Use a NumericUpDown control, if there is one and you can just set the Minimum and Maximum properties.

如果没有,在文本框的 KeyDown 事件中使用它:

If there's not, use this in the KeyDown event of the textbox:

List<Keys> allowedKeys = new List<Keys>()
{
    Keys.Back, Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5,
    Keys.NumPad0, Keys.NumPad1, Keys.NumPad2, Keys.NumPad3, Keys.NumPad4, Keys.NumPad5
};

e.SuppressKeyPress = !allowedKeys.Contains(e.KeyCode);

这将抑制任何不是 0-5BACKSPACE 键的东西.此外,将您的 Maximum Length 属性设置为 1,它将允许 only 0 到 5.

This will suppress anything that is not a 0-5 or BACKSPACE key. Also, set your Maximum Length property to 1, it will allow only 0 through 5.

这篇关于如何创建仅接受某些整数值的文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆