Geeks With Blogs

News
Michael Crump Microsoft MVP, INETA Community Champion and XAML Advocate.

I’ve been answering this question over and over about TextBox validation on the MSDN forums. I wanted to post it on my blog as a point of reference for future users. Basically the question is, I have a textbox and want to restrict numeric values or alpha only. I’ve seen so many version of this involving Regular Expressions to some crazy alpha/numeric array searches. Below is the method that I am using in several production apps as well as community apps. I hope this helps the people on the MSDN forums as well as any one else.

 

//For limiting to access numbers
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 

{ 
 if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 

  e.Handled = true; 
 
 // To allow only one decimal point 
 if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 

    e.Handled = true; 
}

//For limiting to use alphabets
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e) 

{ 
 if (Char.IsLetter(e.KeyChar) || Char.IsSeparator(e.KeyChar) || Char.IsPunctuation(e.KeyChar)) 
  // Allow input. 
  e.Handled = false; 

 else 
  // Stop the character from being entered into the control since not a letter, nor punctuation, nor a space. 
  e.Handled = true; 

} 

To check for a certain numbers of characters in textbox.
Int n = Regex.Matches(TextBox1.Text, "[a-zA-Z]").Count;
Posted on Sunday, June 27, 2010 9:07 PM General C# | Back to top

Copyright © mbcrump | Powered by: GeeksWithBlogs.net