限制输入类型

本文提供了使用C#实现的代码示例,展示了如何限制Windows窗体中的文本框仅接受字符或数字输入,并通过正则表达式验证数字的有效性。

一、只允许字符输入

 1private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
 2        {
 3            //控制为字符输入
 4            if (this.textBox4.Text.Length == 0)
 5            {
 6                if (Char.IsLetter(e.KeyChar))
 7                    e.Handled = false;
 8                else e.Handled = true;
 9            }

10            else
11            {
12                if (Char.IsLetter(e.KeyChar) || (Keys)e.KeyChar == Keys.Back )
13                {
14                    e.Handled = false;
15                }

16                else
17                {
18                    e.Handled = true;
19                }

20            }

21        }

22

二、只允许数字输入
 1private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
 2        {
 3            //控制为数字输入
 4            if (this.textBox5.Text.Length == 0)
 5            {
 6                if (Char.IsDigit(e.KeyChar))
 7                    e.Handled = false;
 8                else e.Handled = true;
 9            }

10            else
11            {
12                if (Char.IsDigit(e.KeyChar) || (Keys)e.KeyChar == Keys.Back || e.KeyChar.ToString() == ".")
13                {
14                    e.Handled = false;
15                }

16                else
17                {
18                    e.Handled = true;
19                }

20            }

21}

22

三、判断数字输入(方法二)
 1/**//// <summary>
 2        /// 判断是否数字
 3        /// </summary>
 4        /// <param name="itemValue"></param>
 5        /// <returns></returns>

 6        private bool IsNumeric(string itemValue)
 7        {
 8            Regex regex = new Regex("^(-?[0-9]*[.]*[0-9]{0,3})$");
 9
10            return regex.IsMatch(itemValue);
11        }

12
13using System.Text.RegularExpressions;
14
15其他情况可以在里面可以找到。char.下面有好多类型。
16

转载于:https://www.cnblogs.com/winnxm/archive/2007/09/29/911174.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值