C# textBox控件只允許為數字和小數點並且提取出這個數字


一、 textBox控件實現只允許為數字和小數點

如下圖所示,在textBox控件框內輸入只能是

要在textBox控件屬性設置按鍵按下的事件觸發,如下圖所示:

二、源代碼

textBox控件只允許為數字和小數點:

private void textBoxVolMax_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 (textBoxVolMax.Text.Length <= 0)
                    e.Handled = true;   //小數點不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBoxVolMax.Text, out oldf);
                    b2 = float.TryParse(textBoxVolMax.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }

把數字提取出來:

if (textBoxVolMax.Text == "")   //textBoxVolMax輸入框為空不去處理
            {
                
            }
            else
            {
                Double MaxValue = Convert.ToDouble(textBoxVolMax.Text);//將字符串轉換為數字
                
                textBoxVolMin.Text = MaxValue.ToString();

            }

三、參考文檔

https://jingyan.baidu.com/article/ad310e80c333f41849f49e31.html

by 羊羊得億
2018-04-02 ShenZhen


免責聲明!

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



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