Click here to Skip to main content
15,913,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want textbox to allow letters,backspace,space,commas and dots on KeyPress Event ...

Please give me suggestion for this...

I have my code something like this

C#
public void Check(Object sender, KeyPressEventArgs e)
        {
            if (!char.IsLetter(e.KeyChar))
            {
                e.Handled = true;
            }
            if (char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space )
            {
&
                // These characters may pass
                e.Handled = false;
            }
            else
            {
                // Everything that is not a letter, nor a backspace nor a space will be blocked
                e.Handled = true;
            }


        }
Posted
Updated 12-Jul-20 4:10am
Comments
Sandeep Mewara 14-May-12 5:29am    
And the issue is?

Its better to use the regular expression for that text box ..
Go through this link it will better useful to you to understand regular expression..

http://msdn.microsoft.com/en-us/library/ff650303.aspx[^]

I hope you have got it..
 
Share this answer
 
 
Share this answer
 
Hi,


C#
public void Check(Object sender, KeyPressEventArgs e)
       {
           //if (!char.IsLetter(e.KeyChar)||!char.IsNumber(e.KeyChar))
           //{
           //    e.Handled = true;
           //}
           if (char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space || e.KeyChar=='.' || e.KeyChar==',' ||char.IsNumber(e.KeyChar))
           {

               // These characters may pass
               e.Handled = false;
           }
           else
           {
               // Everything that is not a letter, nor a backspace nor a space will be blocked
               e.Handled = true;
           }


       }
 
Share this answer
 
it is very simple to use and always I use like this


char chr = e.KeyChar;
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && chr!=',' && chr!='.' && chr!=8)
{
e.Handled = true;
//some statements like MessageBox.Show("Please Enter Valid Value");
}
// 8 stands for backspace
so your textbox only accepts dot,comman, backspace,space and letters other than that it will produce "please enter valid value".
 
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