-5

I have a Windows application, in which there is a login form and registration form. In the registration form there are 4 textboxes in which one of them is for getting the user contact number (Mobile Number), where only numbers are allowed. I want that user can enter only integer number not char just like in asp application, where using ajax textfilter we restrict the user to enter only integer number.

Does this type of functionality exist, such that the Windows application can restrict the user?

Mark J. Bobak
  • 13,720
  • 6
  • 39
  • 67
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85

1 Answers1

0

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 enter image description here Change the masked property of maskedTextBox to Digits like this:- enter image description here

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

Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97