c# TextBox只能输入数字的处理方法

//选择文本框的事件窗口,找到按键输入的方法KeyPress,双击建立新的方法。
private
void textBox6_KeyPress(object sender, KeyPressEventArgs e) { var textBox1 = (TextBox)sender; //判断按键是不是要输入的类型。 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46) e.Handled = true; //小数点的处理。 if ((int)e.KeyChar == 46) //小数点 { if (textBox1.Text.Length <= 0) e.Handled = true; //小数点不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(textBox1.Text, out oldf); b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } }

猜你喜欢

转载自www.cnblogs.com/zhoushuang0426/p/10470349.html