一、 textBox控件实现只允许为数字和小数点
如下图所示,在textBox
控件框内输入只能是
要在textBox
控件属性设置按键按下的事件触发,如下图所示:
二、源代码
textBox控件只允许为数字和小数点:
private void textBoxVolMax_KeyPress(object sender, KeyPressEventArgs e) { //判断按键是不是要输入的类型 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 (textBoxVolMax.Text.Length <= 0) e.Handled = true; //小数点不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(textBoxVolMax.Text, out oldf); b2 = float.TryParse(textBoxVolMax.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } }
把数字提取出来:
if (textBoxVolMax.Text == "") //textBoxVolMax输入框为空不去处理 { } else { Double MaxValue = Convert.ToDouble(textBoxVolMax.Text);//将字符串转换为数字 textBoxVolMin.Text = MaxValue.ToString(); }
转载:cnblogs.com/yangxuli/p/8692926.html