[WinForm]TextBox只能输入数字或者正浮点型数字_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > [WinForm]TextBox只能输入数字或者正浮点型数字

[WinForm]TextBox只能输入数字或者正浮点型数字

 2014/10/18 10:39:52  楚人游子  程序员俱乐部  我要评论(0)
  • 摘要:关键代码:///<summary>///只能输入数字【KeyPress事件】///</summary>///<paramname="textBox">TextBox</param>///<paramname="e">KeyPressEventArgs</param>publicstaticvoidOnlyInputNumber(thisTextBoxtextBox
  • 标签:for winform

关键代码:

class="csharpcode">        /// <summary>
        /// 只能输入数字【KeyPress事件】
        /// </summary>
        /// <param name="textBox">TextBox</param>
        /// <param name="e">KeyPressEventArgs</param>
        public static void OnlyInputNumber(this TextBox textBox, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        /// <summary>
        /// 只能输入正浮点型数字【KeyPress事件】
        /// </summary>
        /// <param name="textBox">TextBox</param>
        /// <param name="e">KeyPressEventArgs</param>
        public static void OnlyInputFloat(this TextBox textBox, KeyPressEventArgs e)
        {
            TextBox _curTextBox = textBox;
            if (e.KeyChar == 46)
            {
                if (_curTextBox.Text.Length <= 0)
                {
                    e.Handled = true;
                }
                else
                {
                    string _txtValue = _curTextBox.Text.Trim();
                    float _newValue, _oldValue;
                    bool _oldResult = false, _newResult = false;
                    _oldResult = float.TryParse(_txtValue, out _oldValue);
                    _newResult = float.TryParse(_txtValue + e.KeyChar.ToString(), out _newValue);
                    if (!_newResult)
                    {
                        if (_oldResult)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }

代码使用:

        private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox _curTextBox = sender as TextBox;
            _curTextBox.OnlyInputNumber(e);
        }
        private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox _curTextBox = sender as TextBox;
            _curTextBox.OnlyInputFloat(e);
        }
希望有所帮助!微笑
发表评论
用户名: 匿名