C# 文本框限制大全

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yujing1314/article/details/84861903

双击事件中的KeyPress事件

1.只能输入数字和字母,退格键:

//文本框限制只能输入数字和字母,退格键:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z')
                || (e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

2.只能输入数字

#region//只能输入数字
            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 (txtPassWord.Text.Length <= 0)

                    e.Handled = true;   //小数点不能在第一位

                else

                {

                    float f;

                    float oldf;

                    bool b1 = false, b2 = false;

                    b1 = float.TryParse(txtPassWord.Text, out oldf);

                    b2 = float.TryParse(txtPassWord.Text + e.KeyChar.ToString(), out f);

                    if (b2 == false)

                    {

                        if (b1 == true)

                            e.Handled = true;

                        else

                            e.Handled = false;

                    }

                }

            }
            #endregion

3.只能输入汉字

 private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入汉字
            Regex rg = new Regex("^[\u4e00-\u9fa5]$");
            if (!rg.IsMatch(e.KeyChar.ToString()))
            {
                e.Handled = true;
            }
        }

猜你喜欢

转载自blog.csdn.net/yujing1314/article/details/84861903
今日推荐