Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
sir i try to restrict textbox only contain number not character or Symbol but i get problem to do this task.......


plz help me....
Posted

Try this:-
C#
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z'))
      {
           e.Handled = true;
           MessageBox.Show("Enter only Number not Character.", "TextBox Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
       }
}


Your Problem is solved.
 
Share this answer
 
v2
Comments
Shambhoo kumar 18-Aug-12 1:19am    
Thanks...
Ank_ush 18-Aug-12 8:46am    
Welcome...
Ank_ush 18-Aug-12 8:46am    
Just vote my answer and accept as solution.
fjdiewornncalwe 28-Aug-12 9:12am    
So what happens when a user clicks on the arrow keys, or delete, or enter. These are all still valid keystrokes that must be considered.
Ank_ush 28-Aug-12 13:20pm    
Arrow Buttons, Enter button, etc they donot enter text when pressed, they have different behaviour.
Hi friend.
try this:

C#
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     e.Handled = !(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar));
}
 
Share this answer
 
v3
Comments
Shambhoo kumar 18-Aug-12 1:18am    
Thanks..
[no name] 28-Aug-12 7:23am    
I think your solution will do just the opposite, did you try it before posting?

EDIT: I see that you have edited the code. Should work now.
fjdiewornncalwe 28-Aug-12 9:13am    
So what happens when a user clicks on the arrow keys, or delete, or enter. These are all still valid keystrokes that must be considered.
[no name] 28-Aug-12 9:29am    
You are right; but I just give him/her a lead.
Anyway I improved my solution.
Also use this one

C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
       {
            if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9)||(e.KeyCode==Keys.Enter)||(e.KeyCode>=Keys.Up && e.KeyCode<=Keys.Down)||(e.KeyCode==Keys.Left))


           {
           }
           else
           {
               textBox1.Text = "";
           }
       }


i agree with you Marcus Kramer

regards
sarva
 
Share this answer
 
v4
Comments
Shambhoo kumar 18-Aug-12 1:19am    
Thanks.
Sarrrva 18-Aug-12 11:15am    
welcome friend!!!!
fjdiewornncalwe 28-Aug-12 9:12am    
So what happens when a user clicks on the arrow keys, or delete, or enter. These are all still valid keystrokes that must be considered.

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