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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章