I have an NumericTextBox component that extends an TextBox in my WinForms application. To filter the characters that is inputed on the textbox I overrided the OnKeyPress method and check for the numeric KeyCodes from Keys enum.
This is working great.
My problem is to extend more this NumericTextBox, so I created a CurrencyTextBox and put in that coe for formattings and etc…
My solution to make my NumericTextBox extendable was to create a Method with an char array for the accepted chars for this textbox that is not numbers. So in my OnKeyPress Method I iterate on my char array to check if the key pressed is inside and permit this key.
My problem is that in my NumericTextBox since I let only numbers to be typed I can’t type commas and periods, in the KeyPress the code has the OEMComma and OEMPeriod that are not the same codes from the chars (‘,’, ‘.’).
My code that checks for the accepted chars looks like this:
protected override void OnKeyDown(KeyEventArgs e)
{
...
var acceptedChars = false;
// AcceptedChars is a String Property with all chars that this textBox should accept
foreach (var acceptedChar in AcceptedChars.ToCharArray())
{
if (acceptedChar == Convert.ToChar(e.KeyCode))
{
acceptedChars = true;
break;
}
}
...
}
When I hit the comma the KeyCode comes with 188 that is the OEMComma, the Convert.ToChar() function convert it to ‘1/4’.
PS: I’m not using the OnKeyPress event because I want to prevent the typing and not correct what was typed.
tis worked for me:
the magic is setting e.Handled = true, that way character never gets to textbox