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


设置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

猜你喜欢

转载自blog.csdn.net/xsfqh/article/details/79985335