c#文本框限制输入内容

时间:2023-03-08 20:39:42
c#文本框限制输入内容
 //限制输入不能为中文和全角
        private void zhbh_KeyPress(object sender, KeyPressEventArgs e)
        {
            int chfrom = Convert .ToInt32("4e00", 16);    //范围(0x4e00~0x9fa5)转换成int(chfrom~chend)
            int chend = Convert .ToInt32("9fa5", 16);
            if (e.KeyChar >= (Char )chfrom && e.KeyChar <= (Char)chend)
            {
                e.Handled = true;
            }
            if (e.KeyChar >= (Char )65281 & (int)e.KeyChar <= ( Char)65374)
            {
                e.Handled = true;
            }
        }
//*******以下方法需在文本框的KeyPress方法下调用
        //限制输入只能为数字
        private void wz_qsh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char .IsNumber(e.KeyChar)) && e.KeyChar != (Char)8)
            {
                e.Handled = true;
            }
        }
 /**
         * 限制只能输入数字和小数点
         * */
        public void validationOnlyFloat(KeyPressEventArgs e, TextBox t)
        {
            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 (t.Text.Length <= 0)
                    e.Handled = true;   //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false , b2 = false;
                    b1 = float.TryParse(t.Text, out oldf);
                    b2 = float.TryParse(t.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false )
                    {
                        if (b1 == true )
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }