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

关键代码:

        /// <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);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }希望有所帮助![WinForm]TextBox只能输入数字或者正浮点型数字

上一篇:Nginx常用功能


下一篇:lucene、lucene.NET详细使用与优化详解