你可以用numericUpDown 控件!
或者每个文本框都添加KeyPress 事件,比较多,但每个文本框里面就复制一行语句 InputDecimalDot(sender, e);
//文本框事件 你自己的
private void txtServiceRate_KeyPress(object sender, KeyPressEventArgs e)
{
InputDecimalDot(sender, e);
}
///<summary>
///公共调用的方法
///文本框只能输入数字和小数点,并且不能大于等于100
///</summary>
public void InputDecimalDotAndLessHundred(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//检测是否已经输入了小数点
bool IsContainsDot = ((TextBox)sender).Text.Contains(".");
int index = ((TextBox)sender).Text.Trim().IndexOf(".");
string l_strText = ((TextBox)sender).Text;
double l_dTest = 0;
if (double.TryParse(l_strText, out l_dTest) && double.Parse(l_strText) >= 100)
{
MessageBox.Show("不能大于100", "提示信息");
e.Handled = true;
}
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8) && (e.KeyChar != 46) && (e.KeyChar != 13))
{
MessageBox.Show("只能输入数字", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Handled = true;
}
else if (IsContainsDot && (e.KeyChar == 46))
{
//如果输入了小数点,并且再次输入
e.Handled = true;
}
else if (index == 0)
{
((TextBox)sender).Text = "";
}
}