.net c# winform TextBox 限制只能输入数字,小数点并最大到2位
只需要处理 KeyPress 事件即可,代码如下
private void ztxtfive_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
{
e.Handled = true;
}
if (e.KeyChar == (char)('-'))
{
if ((sender as TextBox).Text != "") { e.Handled = true; }
}
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
{
e.Handled = true;
}
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0))
e.Handled = true;
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
{
e.Handled = true;
}
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
{
e.Handled = true;
}
if (e.KeyChar != '\b' && (((TextBox)sender).SelectionStart) > (((TextBox)sender).Text.LastIndexOf('.')) + 2 && ((TextBox)sender).Text.IndexOf(".") >= 0)
e.Handled = true;
if (e.KeyChar != '\b' && ((TextBox)sender).SelectionStart >= (((TextBox)sender).Text.LastIndexOf('.')) && ((TextBox)sender).Text.IndexOf(".") >= 0)
{
if ((((TextBox)sender).SelectionStart) == (((TextBox)sender).Text.LastIndexOf('.')) + 1)
{
if ((((TextBox)sender).Text.Length).ToString() == (((TextBox)sender).Text.IndexOf(".") + 3).ToString())
e.Handled = true;
}
if ((((TextBox)sender).SelectionStart) == (((TextBox)sender).Text.LastIndexOf('.')) + 2)
{
if ((((TextBox)sender).Text.Length - 3).ToString() == ((TextBox)sender).Text.IndexOf(".").ToString()) e.Handled = true;
}
}
if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0")
{
e.Handled = true;
}
}