C# TextBox中只能輸入數字

 private void Form1_Load(object sender, EventArgs e)

        {

            this.txtBox.GotFocus += new EventHandler(txtBox_GotFocus);

        }

        //給只許輸入數字的輸入框複製/粘貼時使用
        private struct StruPastText
        {
            public string _text;
            public int _selStart;
            public int _selLength;
            public StruPastText(string txt, int Start, int Length)
            {
                _text = txt;
                _selStart = Start;
                _selLength = Length;
            }
        }

        private StruPastText _pastText = new StruPastText();

        private void txtBox_GotFocus(object sender, EventArgs e)
        {
            this.NotePastText(this.txtBox, ref _pastText);
        }     

        private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.CheckKeyIn(e, false);
        }

        private void txtBox_TextChanged(object sender, EventArgs e)
        {
            if (this.IsNumeric(this.txtBox.Text.ToString().Trim(), true, false))
            {
                this.NotePastText(this.txtBox, ref _pastText);
            }
            else
            {
                this.RestoreText(this.txtBox, _pastText);
            }
        }


        private void CheckKeyIn(KeyPressEventArgs Key, bool AllowDot)
        {
            if (Char.IsControl(Key.KeyChar)) return;//注:回退键也属于控制键之一.
            if (Char.IsDigit(Key.KeyChar)) return;
            if (Key.KeyChar == '.')
            {
                if (!AllowDot) Key.KeyChar = (char)0;
                return;
            }
            Key.KeyChar = (char)0;
        }

      
        private bool IsNumeric(string NumStr, bool MayEmpty, bool ContainDot)
        {
            //检查空值
            if (NumStr + "" == "")
            {
                if (MayEmpty)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            //检查小数点
            if (ContainDot)
            {
                int DotPos = NumStr.IndexOf('.');
                if (DotPos >= 0)
                {
                    DotPos = NumStr.IndexOf('.', DotPos + 1);
                    if (DotPos >= 0) return false;
                }
            }
            else
            {
                if (NumStr.IndexOf('.') >= 0) return false;
            }
            //检查各位数字
            char[] ChrArr = NumStr.ToCharArray();
            for (int i = 0; i <= ChrArr.GetUpperBound(0); i++)
            {
                if (!Char.IsDigit(ChrArr[i]))
                {
                    if (ChrArr[i] != '.') return false;
                    if (!ContainDot) return false;
                }
            }
            if (ContainDot)
            {
                if (NumStr.Replace('.', (char)0).Length <= 0) return false;//判断是否只含有".",如果只含有".",而无数字,返回错误.
            }
            //检查正确
            return true;
        }

        /// <summary>
        /// 因为用TextBox控件的Undo()方法有时效果不好,或者不灵,故用NotePastText方法和RestoreText方法来实现"取消"的效果.
        /// </summary>
        /// <param name="txtRestoreTo"></param>
        /// <param name="TextFrom"></param>
        private void RestoreText(TextBox txtRestoreTo, StruPastText TextFrom)
        {
            txtRestoreTo.Text = TextFrom._text;
            txtRestoreTo.SelectionStart = TextFrom._selStart;
            txtRestoreTo.SelectionLength = TextFrom._selLength;
        }
        /// <summary>
        /// 因为用TextBox控件的Undo()方法有时效果不好,或者不灵,故用NotePastText方法和RestoreText方法来实现"取消"的效果.
        /// </summary>
        /// <param name="txtFrom"></param>
        /// <param name="NoteTo"></param>
        private void NotePastText(TextBox txtFrom, ref StruPastText NoteTo)
        {
            NoteTo._text = txtFrom.Text;
            NoteTo._selStart = txtFrom.SelectionStart;
            NoteTo._selLength = txtFrom.SelectionLength;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值