C# 中怎么设置TextBox中只允许输入数字,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
解决方法
代码实现
我们在自己增加的textBox控件中的KeyPress时间中输入如下代码
private void textBox1_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 (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;
}
}
}
}
看完上述内容,你们掌握C# 中怎么设置TextBox中只允许输入数字的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!