C#設置textBox只能輸入數字(正數,負數,小數)簡單實現


*設置textBox只能輸入數字(正數,負數,小數)

        */
         public static bool NumberDotTextbox_KeyPress( object sender, KeyPressEventArgs e)
         {
             //允許輸入數字、小數點、刪除鍵和負號
             if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != ( char )( '.' ) && e.KeyChar != ( char )( '-' ))
             {
                 return true ;
             }
             if (e.KeyChar == ( char )( '-' ))
             {
                 if ((sender as TextBox).Text != "" )
                 {
                     return true ;
                 }
             }
             //小數點只能輸入一次
             if (e.KeyChar == ( char )( '.' ) && ((TextBox)sender).Text.IndexOf( '.' ) != -1)
             {
                 return true ;
             }
             //第一位不能為小數點
             if (e.KeyChar == ( char )( '.' ) && ((TextBox)sender).Text == "" )
             {
                 return true ;
             }
             //第一位是0,第二位必須為小數點
             if (e.KeyChar != ( char )( '.' ) && e.KeyChar != 8 && ((TextBox)sender).Text == "0" )
             {
                 return true ;
             }
             //第一位是負號,第二位不能為小數點
             if (((TextBox)sender).Text == "-" && e.KeyChar == ( char )( '.' ))
             {
                 return true ;
             }
 
             return false ;
         }
 
         public static bool NumberTextbox_KeyPress(KeyPressEventArgs e)
         {
             if (e.KeyChar != '\b' ) //這是允許輸入退格鍵
             {
                 if ((e.KeyChar < '0' ) || (e.KeyChar > '9' )) //這是允許輸入0-9數字
                 {
                     return true ;
                 }
             }
 
             return false ;
         }


免責聲明!

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



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