C# TextBox 只能输入数字

时间:2024-01-01 22:57:45
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox txt = sender as TextBox;
//屏蔽非法按键,只能输入小数
if ((e.KeyChar >= '' && e.KeyChar <= '') || e.KeyChar == '-' || e.KeyChar == '.' || e.KeyChar == )
{
if (txt.Text.Contains(".") && e.KeyChar == '.')
{
e.Handled = true;
}
else if (e.KeyChar == '-')
{
if (txt.Text.Length != )
{
e.Handled = true;
}
}
}
else
{
e.Handled = true;
}
}