1、TextBox 只可输入数字(例如:0.123,15,46.1等)
private void txtStartNumber_KeyPress(object sender, KeyPressEventArgs e)
{
//IsNumber:指定字符串中位于指定位置的字符是否属于数字类别
//IsPunctuation:指定字符串中位于指定位置的字符是否属于标点符号类别
//IsControl:指定字符串中位于指定位置的字符是否属于控制字符类别
if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true; //获取或设置一个值,指示是否处理过System.Windows.Forms.Control.KeyPress事件
}
else if (Char.IsPunctuation(e.KeyChar))
{
if (e.KeyChar == ‘.’)
{
if (((TextBox)sender).Text.LastIndexOf(‘.’) != -1)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
}
2、TextBox只可输入整数(例如:2,3,45等)
private void txtStartNumber_KeyPress(object sender, KeyPressEventArgs e)
{
//IsNumber:指定字符串中位于指定位置的字符是否属于数字类别
//IsPunctuation:指定字符串中位于指定位置的字符是否属于标点符号类别
//IsControl:指定字符串中位于指定位置的字符是否属于控制字符类别
if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
{
e.Handled = true; //获取或设置一个值,指示是否处理过System.Windows.Forms.Control.KeyPress事件
}
else if (Char.IsPunctuation(e.KeyChar))
{
e.Handled = true;
}
}
3、TextBox只可输入整数(例如:2,3,45等)
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char result = e.KeyChar;
if (char.IsDigit(result) || result == 8)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}