.net c# winform TextBox 限制只能输入整数或小数
只需要处理 KeyPress 事件即可,代码如下
private void ztxtthere_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar)) { e.Handled = false; }
else
{
string str = ztxtthere.Text;
if (e.KeyChar == Convert.ToChar("。") || e.KeyChar == Convert.ToChar("."))
{
int i_d = 0;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == ".")
{
e.Handled = true;
i_d++;
return;
}
}
if (i_d == 0)
{
e.KeyChar = Convert.ToChar(".");
e.Handled = false;
}
}
else if (e.KeyChar == '\b') { e.Handled = false; }
else { e.Handled = true; }
}
}
private void ztxtfour_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.')
{
e.Handled = true; //非以上键则禁止输入
}
string str = ztxtfour.Text;
if (e.KeyChar == '0' && str.Trim() == "") e.Handled = true; //禁止第一个字符就输入0
if (e.KeyChar == '.' && str.Trim() == "") e.Handled = true; //禁止第一个字符就输入小数点
if (e.KeyChar == '.' && str.Contains(".")) e.Handled = true; //禁止输入多个小数点
}