在textbox事件中的KeyPress中双击进入编程
private void txtX1_KeyPress(object sender, KeyPressEventArgs e)
{
limit_txtinput(sender, e);
}
private void limit_txtinput(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 (this.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(this.Text, out oldf);
b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
如果想限制textbox的输入长度则在属性下的MaxLength中进行限制
升级版:可以输入负号
private void txtX1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = limit_txtinput(sender, e);
}
//限制txtBox的输入内容仅可为数字和小数点(小数点不能是首位)
private bool limit_txtinput(object sender, KeyPressEventArgs e)
{
//允许输入数字、小数点、删除键和负号
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
{
return true;
}
if (e.KeyChar == (char)('-'))
{
if ((sender as TextBox).Text != "")
{
return true;
}
}
//小数点只能输入一次
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
{
return true;
}
//第一位不能为小数点
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
{
return true;
}
//第一位是0,第二位必须为小数点
if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0")
{
return true;
}
//第一位是负号,第二位不能为小数点
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
{
return true;
}
return false;
}