C#验证:限制TextBox只能输入数字并控制输入数字的长度(数字)

一.KeyPress事件

private void txt_loopNum_KeyPress(object sender, KeyPressEventArgs e)

        {

            CheckNum(sender, e);

        }

二.CheckNum方法

public void CheckNum(object sender, KeyPressEventArgs e)
        {
            //阻止从键盘输入键
            e.Handled = true;
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || (e.KeyChar == (char)8))
            {
                if (e.KeyChar == (char)8)
                {
                    e.Handled = false; return;
                }
                else
                {
                    int len_lookNum = ((TextEdit)sender).Text.Trim().Length;
                    if (len_lookNum < 8)
                    {
                        if (len_lookNum == 0 && e.KeyChar != '0')
                        {
                            e.Handled = false; return;
                        }
                        else if (len_lookNum== 0)
                        {
                            e.Handled = true; return;
                        }
                        e.Handled = false; return;
                    }
                    else
                    {
                        MessageBox.Show("输入数字过大");
                    }
                }
            }
        }

 

转载于:https://www.cnblogs.com/lqsilly/archive/2013/02/19/2916729.html

你可能感兴趣的:(C#验证:限制TextBox只能输入数字并控制输入数字的长度(数字))