1.输入整数的约束
private void TotalNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) //判断输入数值是否为数字
MessageBox.Show("只能输入数字", "提示",MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Handled = true;
}
}
2.数入整数或小数的约束
private void TotalWeight_KeyPress(object sender, KeyPressEventArgs e)
{
Mystyle.InputNumeric(e, txtTotalWeight);
}
public void InputNumeric(KeyPressEventArgs e, TextBox txt)
{
//在可编辑控件的Text属性为空的情况下,不允许输入".字符"
if (String.IsNullOrEmpty(txt.Text) && e.KeyChar.ToString() == ".")
{
//把Handled设为true,取消KeyPress事件,防止控件处理按键
e.Handled = true;
}
//可编辑控件不允许输入多个"."字符
if (txt.Text.Contains(".") && e.KeyChar.ToString() == ".")
{
e.Handled = true;
}
//在可编辑控件中,只可以输入“数字字符”、".字符" 、"字符"(删除键对应的字符)
if (!Char.IsDigit(e.KeyChar) && e.KeyChar.ToString() != "." && e.KeyChar.ToString() != "")
{
e.Handled = true;
}
//con.Text = e.KeyChar.ToString();
}
3.该方法限定控件只可以接收表示非负整数的字符
public void InputInteger(KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar.ToString() != "")
{
//把Handled设为true,取消KeyPress事件,防止控件处理按键
e.Handled = true;
}
}