Hi guys,
I just wonder how i can validate a TextBox( like txtName) to accept just name string not any numeric value?
Cloud u please let me know how I can do it? should I use a try and catch block?
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Roy SPosted Jun 21, 2010, 12:26 PM
You only need to evaluate every character the user enters in the textbox and if it's a number you just make it go away. This can be done by putting this code at the keyPress event of the textbox:
e.Handled = char.IsNumber(e.KeyChar);
e.Handled: means if the event is already handled or not (if false it will act normal, if true it will look like the user didn't press a key)
char.IsNumber(...): checks if the character is a number
e.keychar: is the character of the key that the user pressed.
So if the character of the key that the user pressed is a number it will look like the user didn't press a key at all.
zhong chenPosted Jun 22, 2010, 11:47 PM
Behrouz HosseiniPosted Jun 22, 2010, 3:08 AM
Thanks a lot for your help. Roy let me thank u more your explanation was perfect.
Sam HobbsPosted Jun 20, 2010, 5:37 PM
Behrouz HosseiniPosted Jun 20, 2010, 3:21 PM
It make sense to write a function by the way that u explain but how I can scan the user input?
"Write code to scan the string for anything that doesn't meet your criteria."
Could you please give me an idea how to do it?!
Best Regards
Bruce RoeserPosted Jun 20, 2010, 1:08 PM
Why not just write a simple function that scans a string and looks for numeric characters? You could write your method like this:
public bool NameIsValid(string nameToValidate) {
// Write code to scan the string for anything that doesn't meet your criteria.
// If it finds anything 'illegal' then return false - otherwise return true.
}
Then in your mainline code (at your save button or something) you could do this:
if (!myLibrary.nameIsValid(TextBox1.Text)) {
MessageBox("Entered name contains garbage in it ... " ...);
TextBox1.Focus();
return;
}
... something like that.
If you wanted to get really sophisticated about it, you could derive your own TextBox class that inherits from the standard textbox and has the additional methods that validate the way you want; though that might be a bit of an overkill! ;-) I don't know offhand whether the TextBox control has an overrideable validation method but you could find that out easily enough. If it does, there you go!
Most developers create their own libraries of custom functions that do things they way they want. The .Net Framework certainly has a ton of functionality but if you develop for very long you're going to want to start assembling a library of functions that do stuff the way you want. This might be a good one to start with.
-bwr-