c # textBox controls only allow to enter numbers and decimal point reprint
// if the key was not the type to be inputted. IF (((int) e.KeyChar <48 || (int) e.KeyChar> 57 is) && (int) = e.KeyChar. 8 && (int) = 46 is e.KeyChar!!) e.Handled = to true; / / processing decimal point. if ((int) e.KeyChar == 46 ) // decimal { IF (textBox1.Text.Length <= 0) e.Handled = to true; // not a decimal point in the first place the else { a float F; oldf a float; BOOL = to false B1, B2 = to false; B1 = float.TryParse (textBox1.Text, oldf OUT); B2 = float.TryParse (textBox1.Text e.KeyChar.ToString + (), OUT F); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } }
Processing only input numbers:
Method a: Private void tBox_KeyPress (Object SENDER, KeyPressEventArgs E) { IF (e.KeyChar == 0x20) e.KeyChar = (char) 0; // spacebar prohibited if ((e.KeyChar == 0x2D) && (( (TextBox) sender) .Text.Length == 0 )) return; // process a negative IF (e.KeyChar> 0x20) { the try { double.Parse (((the TextBox) SENDER) .Text + e.KeyChar.ToString ( )); } the catch { e.KeyChar = (char) 0; // process the illegal characters } } } method two: void TextBox_KeyPress Private (Object SENDER, KeyPressEventArgs E) { IF (! = e.KeyChar Char.IsDigit. 8 && (e.KeyChar)!) { e.Handled = to true; } } or Private void TextBox_KeyPress (Object SENDER, KeyPressEventArgs E) { IF (! e.KeyChar = '\ B' && Char.IsDigit (e.KeyChar)!) { e.Handled = to true; } } method three: Private void textBox1_KeyPress (Object SENDER, System.Windows.Forms.KeyPressEventArgs E) { IF (e.KeyChar! = '\ B') // this is the backspace key allows the input { IF ((e.KeyChar < '0') || (e.KeyChar> '. 9')) // this is 0-9 allow the input { 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 = to true; } } } Method 7: using ASCII code approach, { IF ((e.KeyChar <|| E = 48. the KeyChar> = 57 is) && (= e.KeyChar. 8) && (= 46 is e.KeyChar))!! e.Handled = to true; ================ 48 represents 0, Representative 9,8 behalf spaces 57, 46 stands for the decimal }