Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I just created this condition to block special characters.
it works, but can we make it simpler?
Who can bring me a better solution?


What I have tried:

C#
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '>' || e.KeyChar == '<' || e.KeyChar == '@' || e.KeyChar == '{' || e.KeyChar == '}' || e.KeyChar == '[' || e.KeyChar == ']' || e.KeyChar == '#' || e.KeyChar == '&' || e.KeyChar == '(' || e.KeyChar == ']' || e.KeyChar == '/' || e.KeyChar == '|' || e.KeyChar == '*' || e.KeyChar == '-' || e.KeyChar == '+' || e.KeyChar == '$' || e.KeyChar == '%' || e.KeyChar == '~' || e.KeyChar == 92)
    {
        e.Handled = true;
    }
}
Posted
Updated 8-Apr-20 2:35am

Another way is to use ErrorProvider Component Overview - Windows Forms | Microsoft Docs[^]. You can validate value entered in a textbox and display error icon near the textbox.

Display Error Icons for Form Validation with ErrorProvider Component - Windows Forms | Microsoft Docs[^]
Do not forget to clear error[^] after successful validation.
 
Share this answer
 
Comments
LSB71 10-Apr-20 2:01am    
Thank you very much, excellent I learn it every day
Maciej Los 10-Apr-20 2:18am    
You're very welcome.
Try:
C#
private const string NotAllowed = @"><@{}[]#&()/|*-+$%~\";
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (NotAllowed.Contains(e.KeyChar))
        {
        e.Handled = true;
        }
    }
Or even:
C#
private const string NotAllowed = @"><@{}[]#&()/|*-+$%~\";
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    e.Handled = NotAllowed.Contains(e.KeyChar);
    }
 
Share this answer
 
v2
Comments
Maciej Los 8-Apr-20 8:28am    
%5^;)

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