C# TextBox只能输入数值

实现限制TextBox只能输入数值思路:首先在控件KeyPress事件中过滤非数值字符,但该过程不能保证输入的字符是正确的数值,如:00.01,100.2.3之类还需要进一步处理,可以通过在控件失去焦点LostFocus事件中通过数值转换转为正确数值。

以下为只能输入非负数数值示例:

 private void tb_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox tbObject = (TextBox)sender;
            if (e.KeyChar == '.' && tbObject.Text.IndexOf(".") != -1)
            {
                e.Handled = true;
            }
            if (!((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == '.' || e.KeyChar == 8))
            {
                e.Handled = true;
            }
        }

 

private void tb_LostFocus(object sender, EventArgs e)
        {
            TextBox tbObject = (TextBox)sender;
            try
            {
                tbObject.Text = Convert.ToDouble(tbObject.Text).ToString();
            }
            catch
            {
                tbObject.Text = "";
            }
        }

 

posted @ 2016-05-06 16:46  林中风  阅读(1226)  评论(0)    收藏  举报