Winform--TextBox
TextBox只允许输入数字
方法一(来自罗友军)
public static bool IsNumeric(string itemValue)
{
return (IsRegEx("^(-?[0-9]*[.]*[0-9]{0,3})$", itemValue));
}
方法二(来自博为药库)
private void CellEdit_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.dgvDrugList.CurrentCell.ColumnIndex == 5 || this.dgvDrugList.CurrentCell.ColumnIndex == 7)
{
//若按下的是非数字,则不进行处理; 46 = '.'
if (!(Char.IsNumber(e.KeyChar)) && !(e.KeyChar == (char)Keys.Enter) && !(e.KeyChar == (char)Keys.Left) &&
!(e.KeyChar == (char)Keys.Right) && !(e.KeyChar == (char)Keys.Back) && !(e.KeyChar == 46))
{
e.Handled = true;
}
//当存在小数点时,若再输入小数点将不会进行处理
string str = ((TextBox)sender).Text;
if (str.Contains(".") && (e.KeyChar == 46))
e.Handled = true;
}
}