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

 

 

還有一種方法:直接判斷輸入小數點的時候看是不是第一個或者是否已經有一個小數點就可以了.

if (textBox1.TextLength == 0 || textBox1.Text.Contains("."))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM