限制使用者輸入 只能是數字,小數,負數。
阿新 • • 發佈:2019-01-27
實現使用者輸入只能是數字,小數,負數,且小數和負數只能輸入一次。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13 && e.KeyChar != 45 && e.KeyChar != 46)
{
e.Handled = true;
}
//輸入為負號時,只能輸入一次且只能輸入一次
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) e.Handled = true;
if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) e.Handled = true;
}