0

Blocking Underscore Input in TextBox

Hello All,

I'm trying to block underscore (_) from being entered into a TextBox but I'm having no luck:

private void CoupontextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsSymbol('_'))
    {
        e.Handled = true;
    }
}

Thanks in advance!

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • What does that code do, that you do not want or expect? – Fildor Jul 22 '22 at 18:51
  • @fildor, I'm trying to prevent the user from being able to enter an underscore into a textbox. Would the code above work? Thanks. – user19064227 Jul 22 '22 at 18:56
  • 2
    Is this Winforms or WPF or what are talking about? – Fildor Jul 22 '22 at 19:00
  • If WinForms: You may use PreviewKey to exclude it from being considered as an input key: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.previewkeydown?view=windowsdesktop-6.0 – Fildor Jul 22 '22 at 19:04
  • Typo? It should be `if (e.KeyChar == '_') e.Handled = true;` – Dmitry Bychenko Jul 22 '22 at 19:10
  • Your code _would_ probably work, too, if the condition actually made sense. You need to check what the EventArgs tell you has been pressed. As is, this only checks If '_' is a symbol. Which will be true or false, _always_. – Fildor Jul 22 '22 at 19:14
  • 2
    Does this answer your question? [How to block or restrict special characters from textbox](https://stackoverflow.com/questions/19524105/how-to-block-or-restrict-special-characters-from-textbox) with just one 'special' character, the '_'. – Luuk Jul 22 '22 at 19:14

1 Answers1

1

It seems that you have just a typo:

// if '_' character is a symbol? - no; false will be returned
char.IsSymbol('_')

is always false. You should put something like this

private void CoupontextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    // if character that corresponds key pressed is '_' we handle the message 
    if (e.KeyChar == '_')
    {
        e.Handled = true;
    }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215