private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tsb = sender as TextBox;
if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != 0x2E) //如果不是数字
{
e.Handled = true;
}
if (e.KeyChar == '-')
{
if (tsb.Text.Length == 0)
{
e.Handled = false;
}
else if (tsb.Text[0] == '-')
{
tsb.Text = tsb.Text.Substring(1, tsb.Text.Length - 1);
e.Handled = true;
tsb.Select(tsb.Text.Length, 0);
}
else
{
tsb.Text = '-' + tsb.Text;
e.Handled = true;
tsb.Select(tsb.Text.Length, 0);
}
}
if (e.KeyChar == '.')
{
if (tsb.Text == "")
{
tsb.Text = "0.";
tsb.Select(tsb.Text.Length, 0); //将光标定位到textBox控件的末尾
e.Handled = true;
}
else if (tsb.Text.Contains("."))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
if (tsb.Text.Length == 1 && tsb.Text[0] == '0' && (e.KeyChar != '.' || e.KeyChar != '-')) //当出现连续数字时,去最前面的0
{
tsb.Text = e.KeyChar.ToString();
e.Handled = true;
tsb.Select(tsb.Text.Length, 0);
}
}
C#:设置TextBox控件中只能输入实数
最新推荐文章于 2023-08-27 15:05:31 发布