Several common methods that can only enter numbers in TextBox (C#)

The original website of this article is: http://bbs.bccn.net/thread-205138-1-1.html

private void tBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 0x20) e.KeyChar = (char)0; //Disable the space key
            if ((e.KeyChar == 0x2D) && (((TextBox) sender).Text.Length == 0)) return; //Handle negative numbers
            if (e.KeyChar> 0x20)
            {
                try
                {
                    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
                }
                catch
                {
                    e.KeyChar = (char)0; //Handle illegal characters
                }
            }
        } private void TextBox_KeyPress(object sender, KeyPressEventArgs e)    {

 



    if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar))
    {
      e.Handled = true;
    }
   }
or 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')/ /This is to allow the input of the backspace key { if((e.KeyChar<'0')||(e.KeyChar>'9'))//This is to allow the input of 0-9 numbers { e.Handled = true; } } private void button1_Click(object sender, EventArgs e) 
 












 

 



string text = this.textBox1.Text; 
if (text != null) 
MessageBox.Show(text); 


private void textBox1_Validating(object sender, CancelEventArgs e) 

const string pattern = @"^\d+\.?\d+$"; 
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;
                }
            }      
        }

Guess you like

Origin blog.csdn.net/youarenotme/article/details/72963141