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;
                }
            }


版权声明:本文为duanwenzhi00原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。