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