C# 设置文本框等控件只能输入 正负整数或小数

//摘要: C# 文本输入控件,通过KeyPress事件实现只能输入正负整数和小数的功能      

	  private void Value_KeyPress(object sender, KeyPressEventArgs e)
        {
            var tb = sender as TextBox;

            if (null == tb)
            {
                e.Handled = true; 
                return;
            }

            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46) //数字、Backspace、小数点
            {
                var editText = (tb.Text);

                if (e.KeyChar != 8)
                { 
                    var selStart = tb.SelectionStart;
                    var selLength = tb.SelectionLength;

                    if (selLength > 0) //存在选择的内容,进行替换。
                    {
                        editText = editText.Remove(selStart, selLength);

                        tb.Text = editText;
                        tb.SelectionLength = 0;
                        tb.SelectionStart = selStart;
                    }
                      
                    editText = editText.Insert(selStart, e.KeyChar.ToString());

                    try
                    {
                        //校验新数据是否合法。
                        var newValue = double.Parse(editText);
                        e.Handled = !(newValue >= 0); 
                    }
                    catch (Exception)
                    {
                        e.Handled = true;
                        return;
                    }
                    e.Handled = false;
                }
                else
                    e.Handled = false;
            }
            else
            {
                //正负数切换
                if (e.KeyChar == 45)
                {
                    tb.Text = tb.Text.Contains("-") ? tb.Text.Replace("-", "") : tb.Text.Insert(0, "-");  

                    tb.Select(tb.Text.Length,0);
                }

                e.Handled = true;
            }
        }

你可能感兴趣的:(WinForm)