Click here to Skip to main content
15,920,111 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
i need to restrict my text box from taking space and apostrophe as input.
i have done this for space
e.Handled = (e.KeyChar == (char)Keys.Space );

but i need to restrict apostrophe too.
"'"

any suggestions?
Posted
Comments
Sergey Alexandrovich Kryukov 18-Aug-11 23:29pm    
It depends. WPF, Forms, ASP.NET, what? Tag it. The idea is very similar though.
--SA

Do the same
C#
e.Handled = e.KeyChar == '\'';
 
Share this answer
 
In KeyPress, reject the event (set e.Handled = true) if the character is in your list of disallowed ones.

That doesn't protect you from pasted text, alt-0nnn entry, drag and drop of text to a text field and any other ways your OS might dream up of changing the text in an edit field. So you also need to implement a TextChanged handler which checks to see if any invalid characters are present, and if so, removes them. Don't assign Text inside TextChanged unless you need to make a modification, though, because it resets the caret position and that's really annoying if it happens every keystroke.
 
Share this answer
 
Try this.
e.Handled = (e.KeyChar == (char)Keys.Space) || (e.KeyChar == '\'');
 
Share this answer
 
Comments
greatreddevil 23-Aug-11 1:25am    
it works.. :)
thanks
IF you are making a web application then you can do it in javascript like this

C#
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event)
{
keynum = e.keyCode
}
// For Netscape/Firefox/Opera
else if (e.which)
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`")
{

return false;
}
else {
return true;
}
}
 
Share this answer
 
Comments
greatreddevil 18-Aug-11 5:11am    
actually its desktop form application.
Syed Salman Raza Zaidi 18-Aug-11 5:22am    
you can check for ASCII code of ' and can check for keycode = ASCII of '

You'll get help from here
http://www.december.com/html/spec/ascii.html

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