公共方法如下:
/// <summary> /// 正则表达式验证只能输入数字或字母 /// </summary> /// <param name="pendingString"></param> /// <returns></returns> public bool IsNaturalOrNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9-]+$"); return reg1.IsMatch(str); } /// <summary> /// 正则表达式验证只能输入数字 /// </summary> /// <param name="pendingString"></param> /// <returns></returns> public bool IsNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9-]+$"); return reg1.IsMatch(str); } /// <summary> /// 正则表达式验证只能输入字母 /// </summary> /// <param name="pendingString"></param> /// <returns></returns> public bool IsNatural(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z-]+$"); return reg1.IsMatch(str); }
应用如下:
private void textBox1_TextChanged(object sender, EventArgs e) { if (string.IsNullOrEmpty((sender as TextBox).Text)) return; if (!IsNumber((sender as TextBox).Text)) { this.textBox1.Text = this.textBox1.Text.Substring(0, this.textBox1.Text.Length - 1); this.textBox1.SelectionStart = this.textBox1.Text.Length; return; } }