C# TextBox中只允許輸入數字的方法

 

1.在Winform(C#)中要實現限制Textbox只能輸入數字,一般的做法就是在按鍵事件中處理,
判斷keychar的值。限制只能輸入數字,小數點,Backspace,del這幾個鍵。數字0~9所
對應的keychar爲48~57,小數點是46,Backspace是8,小數點是46。 

2.輸入小數點。輸入的小數要符合數字的格式,類似9.9.9這樣的是不能夠輸入的。做法就是用float.TryParse來轉換Textbox中之前和之後的值,然後比較兩者的轉換結果。

在如下代碼中,實現了控件textBox1中輸入數字。
在控件textBox1中的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;
                        }
                    }
                }
        }


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章