限制整数
private void TextBoxInteger_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b' && !Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
else if(e.KeyChar == '-' && ((TextBox)sender).Text.Length > 1)
{
e.Handled = true;
}
}
限制浮点数
private void TextBoxFloat_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != 0x2E)
{
e.Handled = true;
}
if (e.KeyChar == '.') //允许输入回退键
{
TextBox tb = sender as TextBox;
if (tb.Text == "")
{
tb.Text = "0.";
tb.Select(tb.Text.Length, 0);
e.Handled = true;
}
else if (tb.Text.Contains("."))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}