C#TextBox中只允许输入数字的方法-飞外

1.在Winform(C#)中要实现限制Textbox只能输入数字,一般的做法就是在按键事件中处理,
判断keychar的值。限制只能输入数字,小数点,Backspace,del这几个键。数字0~9所
对应的keychar为48~57,小数点是46,Backspace是8,小数点是46。

2.输入小数点。输入的小数要符合数字的格式,类似9.9.9这样的是不能够输入的。做法就是用float.TryParse来转换Textbox中之前和之后的值,然后比较两者的转换结果。

在如下代码中,实现了控件textBox1中输入数字。
在控件textBox1中的KeyPress时间中输入如下代码

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar 48 || (int)e.KeyChar 57) (int)e.KeyChar != 8 (int)e.KeyChar !=46 )
e.Handled = true;

//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (textBox1.Text.Length = 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(textBox1.Text, out oldf);
b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}


还有一种方法:直接判断输入小数点的时候看是不是第一个或者是否已经有一个小数点就可以了.

if (textBox1.TextLength == 0 || textBox1.Text.Contains("."))