C# winform中限制只能输入小数

1、利用输入框的keypress事件

2、加入如下代码:

          //判断只能输入数字和Backspace
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8)
                e.Handled = true;

 

          //判断可输入小数点,但小数点不能放在数字的前面,且要保证只能输入一个小数点在正确的位置
            if ((int)e.KeyChar == 46)                       //小数点    
            {
                if (tB_UnitPrice.Text.Length <= 0)
                    e.Handled = true;           //小数点不能在第一位    
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(tB_UnitPrice.Text, out oldf);
                    b2 = float.TryParse(tB_UnitPrice.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                    else
                        e.Handled = false;
                }
            }

发布了16 篇原创文章 · 获赞 22 · 访问量 41万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章