Winform TextBox中只能輸入數字的幾種常用方法(C#)


方法一:  
  
private void tBox_KeyPress(object sender, KeyPressEventArgs e)  
  
 {  
            if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格鍵  
            if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //處理負數  
            if (e.KeyChar > 0x20)  
            {  
                try  
                {  
                    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());  
                }  
                catch  
                {  
                    e.KeyChar = (char)0;   //處理非法字符  
                }  
            }  
}  
  
方法二:  
  
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)  
 {  
    if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar))  
    {  
      e.Handled = true;  
    }  
}  
或者  
  
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)  
{  
    if(e.KeyChar!='\b'&&!Char.IsDigit(e.KeyChar))  
    {  
      e.Handled = true;  
    }  
  
}  
  
方法三:  
  
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)  
{  
if(e.KeyChar!='\b')//這是允許輸入退格鍵  
{  
if((e.KeyChar<'0')||(e.KeyChar>'9'))//這是允許輸入0-9數字  
{  
e.Handled = true;  
}  
}  
}  
  
方法四:  
  
private void textBox1_Validating(object sender, CancelEventArgs e)   
{   
const string pattern = @"^\d+\.?\d+{1}quot;;   
string content = ((TextBox)sender).Text;   
  
if (!(Regex.IsMatch(content, pattern)))   
{   
errorProvider1.SetError((Control)sender, "只能輸入數字!");   
e.Cancel = true;   
}   
else   
errorProvider1.SetError((Control)sender, null);   
}  
  
方法五:  
  
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)  
{  
if(e.KeyChar=='.' && this.textBox1.Text.IndexOf(".")!=-1)  
{  
e.Handled=true;  
}  
  
if(!((e.KeyChar>=48 && e.KeyChar<=57) || e.KeyChar=='.' || e.KeyChar==8))  
{  
e.Handled=true;  
}  
  
}  
  
方法六:  
  
private void tbx_LsRegCapital_KeyPress(object sender, KeyPressEventArgs e)  
{  
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))  
            {  
                e.Handled = true;//消除不合適字符  
            }  
            else if (Char.IsPunctuation(e.KeyChar))  
            {  
                if (e.KeyChar != '.' || this.textBox1.Text.Length == 0)//小數點  
                {  
                    e.Handled = true;  
                }  
                if (textBox1.Text.LastIndexOf('.') != -1)  
                {  
                    e.Handled = true;  
                }  
            }        
  }    
  
方法七:  
  
利用ASCII碼處理辦法、  
{  
  
            if ((e.KeyChar <= 48 || e.KeyChar >=57) && (e.KeyChar != 8) && (e.KeyChar != 46))  
              e.Handled = true;  
================48代表0,57代表9,8代表空格,46代表小數點  
}  

 


免責聲明!

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



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