1.设置成只能输入正整数:private void in_amount_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')//这是允许输入退格键
{
int len = in_amount.Text.Length;
if (len < 1 && e.KeyChar == '0')
{
e.Handled = true;
}
else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
{
e.Handled = true;
}
}
}
2.设置成只能输入数字(可包含小数):private void in_amount_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true;//消除不合适字符
}
else if (Char.IsPunctuation(e.KeyChar))
{
if (e.KeyChar != '.' || this.in_amount.Text.Length == 0)//小数点
{
e.Handled = true;
}
if (in_amount.Text.LastIndexOf('.') != -1)
{
e.Handled = true;
}
}
}