Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Make A textBox Accept specific Characters from Keyboard

Status
Not open for further replies.

vtops

IS-IT--Management
Oct 13, 2005
63
GR
Dear All,


How can i make a textbox accept specific characters from keyboard.
While the user press a key i want to check the key. If the key is not that the system was expected do not appear it on the textbox.


For example i would like a textbox accept only numbers.
But if i press any other key except 0-9 do not show it on the textBox.



Best Regards
 
Capture the Keydown event. If the character is numeric then continue to process the keypress and if not, cancel it.


private void textBox1_Keydown(object Sender, KeyEventArgs e)
{
try
{
Convert.ToInt32((char)e.KeyCode);
}
catch
{
e.Handled = true;
}
}
 
Also, if you want to make it specific characters you will want to look at a Regex (Regular Expressions) and do a Match() on the incoming character.

Google Regex C#
 
This is another way to handle this using the KeyPress event. This allows the user to either enter a number or a backspace.

For some reason, with the code above I was still able to type in non-numeric characters.

Code:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if(!Char.IsNumber(e.KeyChar) && e.KeyChar != (char)8)
			{
				e.Handled = true;
			}

		}

The wisest people are those who are smart enough to realize they don't know it all.
 
Thank you everybody!

It is exactly that i was needing


Best Regards
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top