C# TEXTBOX控件限制输入为数值


一、 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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM