[archived content]
Dfl /

Preventing the user from typing unwanted characters into a TextBox.

The below example derives from TextBox and only lets the user enter characters relevant to an integer, including sign characters.

class IntTextBox: TextBox
        protected override void onKeyPress(KeyEventArgs ea)
                        if(!(ea.modifiers & (Keys.ALT | Keys.CONTROL)))
                                switch(ea.keyData) // Key code and modifiers combined.
                                        case Keys.D0:
                                        case Keys.D1:
                                        case Keys.D2:
                                        case Keys.D3:
                                        case Keys.D4:
                                        case Keys.D5:
                                        case Keys.D6:
                                        case Keys.D7:
                                        case Keys.D8:
                                        case Keys.D9:

                                        case Keys.BACK:
                                        case Keys.DELETE:

                                        case Keys.HOME:
                                        case Keys.END:

                                        case Keys.LEFT:
                                        case Keys.RIGHT:
                                        case Keys.UP:
                                        case Keys.DOWN:

                                        break; // Allow the above.


                                        // Numpad.
                                        case Keys.SUBTRACT:
                                        case Keys.ADD:

                                        case Keys.OEM_MINUS:
                                        case Keys.OEM_PLUS | Keys.SHIFT:

                                        if(0 == selectionStart)
                                        break; // Allow the above only at position 0.
                                        goto default;

                                        ea.handled = true; // Prevent key.

Note that the user can still paste any text into it, and it currently doesn't check if the box already contains a sign character.

To use this control in Entice Designer, add a regular TextBox to your form or control, right click the text box and go to its properties, and finally change its type to IntTextBox or what ever you named the class.

Page last modified on March 29, 2007, at 11:59 AM