Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
What's the easiest way to validate a textbox so that the textbox can only except numbers? And an other textbox only except letters?
Posted

Keypress event on the textbox

C#
private void txtSimnr_KeyPress(object sender, KeyPressEventArgs e)
        {
       if (!char.IsControl(e.KeyChar)
       && !char.IsDigit(e.KeyChar)
       && e.KeyChar != '.')
            {
                e.Handled = true;
            }

        }
 
Share this answer
 
v2
The following are some of the alternatives

1. Use MaskedTextBox (this is easiest approach) explained here
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx[^]
2. In the KeyPress event if the Key pressed is not the required character then set e.Handled = true
3. In the KeyDown event if the key pressed is not the required character then set
e.SuppressKeyPress = true
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900