[C#上位机学习]文本框只允许输入数字整数或浮点数

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
       {  
             
           //允许输入数字、小数点、删除键和负号  
           if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))  
           {  
               MessageBox.Show("请输入正确的数字");  
               this.textBox1.Text = "";  
               e.Handled = true;  
           }  
           if (e.KeyChar == (char)('-'))  
           {  
               if (textBox1.Text != "")  
               {  
                   MessageBox.Show("请输入正确的数字");  
                   this.textBox1.Text = "";  
                   e.Handled = true;  
               }  
           }  
           //小数点只能输入一次  
           if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)  
           {  
               MessageBox.Show("请输入正确的数字");  
               this.textBox1.Text = "";  
               e.Handled = true;  
           }  
           //第一位不能为小数点  
           if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")  
           {  
               MessageBox.Show("请输入正确的数字");  
               this.textBox1.Text = "";  
               e.Handled = true;  
           }  
           //第一位是0,第二位必须为小数点  
           if (e.KeyChar != (char)('.') && ((TextBox)sender).Text == "0")  
           {  
               MessageBox.Show("请输入正确的数字");  
               this.textBox1.Text = "";  
               e.Handled = true;  
           }  
           //第一位是负号,第二位不能为小数点  
           if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))  
           {  
               MessageBox.Show("请输入正确的数字");  
               this.textBox1.Text = "";  
               e.Handled = true;  
           }  
       }  

此文转载于网络

posted @ 2022-04-03 23:42  2020年2月1日13点30分  阅读(202)  评论(0)    收藏  举报