Search code examples
c#visual-studiotextboxkeypresskeyboard-events

TextBox1_KeyPress will not work anymore even though I haven't changed any code


Recently I switched from Visual Studio express 2013 to Visual Studio Community 15. When I would run my form with this bit of code that is supposed to prevent character input an only allow number and decimal(.) to the textbox and it ran perfectly, but once I switched to Community 15 it no longer prevented character input. WHY? handled is set to false as long as its a digit or decimal?

private void WeeklyCheckTxtBox_KeyPress(object sender, KeyPressEventArgs e)
    {
       if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation('.'))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Solution

  • The issue is that char.IsPunctuation('.') will always return true as . is inarguably a punctuation symbol, and so the event will always be unhandled - I think you may have meant to write e.KeyChar == '.' or char.IsPunctuation(e.KeyChar).