How to ignore special char from all text fields?

Haa912005

New member
Joined
Jul 28, 2019
Messages
1
Programming Experience
3-5
Hello friends,
I created a win form application using C#
I want to ignore the user to enter special char '@' and apply this policy in all text fields in my application.
How can I do this??
Thanks..
 
What EXACTLY do you mean by "ignore"? You need to be specific because it could be interpreted in a number of ways and we shouldn't have to guess which you mean. My guess would be that you mean that, if the user attempts to enter certain characters, they are discarded and not entered into the text of the control. If that's the case, you can handle the KeyPress event and set e.Handled to true to reject the current character, which you will find in the e.KeyChar property.
 
Try this answer. It's inline with what John was saying above. I gave you a function because you said you wanted to ignore from all text fields. Each of your text fields will need a KeyPressEvent. So in your windows forms design mode, click one of your textboxes and click the lightening icon on the bottom right of your properties box, and look for Key Press, select the empty box beside it and hit enter. Then apply the code below to said event. Example tested and working.

Look at my console below, to see how she outputs ::
C#:
        private bool CharAllowed(KeyPressEventArgs e) /* Check if char is allowed */
        {
            switch (e.KeyChar.ToString()) /* I used the string representation of the char to match case */
            {
                case "@":
                    return false;
                default: /* These will be allowed symbols. Disallowed symbols should have their own case and return false as is above */
                    {
                        return true; /* Allowed values should return true */
                    }
            }
        }

        private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool b = CharAllowed(e); /* Pass the event args of the Key press events and let the Char Allowed function decide if its a symbol you allow */
            if (b) { Console.WriteLine(string.Concat(e.KeyChar.ToString(), " : Symbol allowed")); }
            else { e.Handled = true; Console.WriteLine(string.Concat(e.KeyChar.ToString(), " : Symbol not allowed")); }
        }
C#:
irCPboi.gif
 
Back
Top Bottom