1)You can handle the TextChanged
event of the TextBox
and make sure that no key other than the digits(0-9) are displayed in the TextBox
.
You can use Regex
to check whether the text contains letters or not.
Another option is to validate input of text before processing the text, if it contains characters other than numbers, issue a warning to the user and allow him to change the text of the TextBox
.
private void Text_Changed(object sender, EventArgs e )
{
if(!char.isDigit(textBox1.Text[textBox1.Text.Length-1]))
{
string temp = string.SubString(textBox1.Text, 0, textBox1.Text.Length-1) ;
textBox1.Text = temp ;
}
}
WORKING:-
Every time the text changes, it checks the last character added and if it's not a digit then,it doesn't display it.
For eg if after entering 971 I enter r then the if
condition becomes true and the Text
field of TextBox
resets the text to 971 and doesn't display the "r".
2)Otherwise, you can use a MaskedTextBox
Change the masked property of maskedTextBox to Digits like this:-

Check the following link:
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx
http://www.codeproject.com/Tips/666932/Using-Masked-TextBox-in-NET
http://www.codeproject.com/Articles/1534/Masked-C-TextBox-Control
3)OPTION-3:- You can create a custom control after deriving from the TextBox
class.
http://msdn.microsoft.com/en-us/library/ms229644(v=vs.90).aspx