C# DEV TextEdit 设置文本框只能输入数字(整数)

转:https://blog.csdn.net/qq_23126581/article/details/70312433

介绍下,设置TextEdit 设置文本框只能输入数字(整数):

在TextEdit里 找到 Mask属性

代码设置:

MaskType="RegEx" UseMaskAsDisplayFormat="True" Mask="[0-9]*"     //这个是允许文本框输入数字(整数),比如22222222222

MaskType="RegEx" UseMaskAsDisplayFormat="True" Mask="([0-9]{1,}[.][0-9]*)"   //这个是允许文本框输入数字,比如22,356.1,78.01

正则表达式: [0-9]*  代表可以输入整数
正则表达式:([0-9]{1,}[.][0-9]*) 代表可以输入数字,包括整数和小数

设置器里设置:


上面是介绍是让textEdit只能输入正整数,接下来介绍让textEdit,textBox等只能输入正数,这个是允许输入小数点的,比如23.1    2.66 

 #region 控制textBox1只能输入正数(包括小数)
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;
            //小数点的处理。
            if ((int)e.KeyChar == 46)                           //小数点
            {
                if (textBox1.Text.Length <= 0)
                    e.Handled = true;   //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBox1.Text, out oldf);
                    b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }
        #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值