定义控件的KeyPress事件,事件中输入如下代码
private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
{
//数字0~9所对应的keychar为48~57,小数点是46,Backspace是8
e.Handled = true;
//输入0-9和Backspace del 有效
if ((e.KeyChar >= 47 && e.KeyChar <= 58) || e.KeyChar == 8)
{
e.Handled = false;//符合条件的进入
}
if (e.KeyChar == 46)//小数点
{
if (txtGRWT.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
if (float.TryParse(txtGRWT.Text + e.KeyChar.ToString(), out f))
{
e.Handled = false;
}
}
}
}