views:

526

answers:

3

I need to validate characters entered by the user in a MaskedTextBox. Which characters are valid depends on those already entered. I've tried using IsInputChar and OnKeyPress, but whether I return false in IsInputChar or set e.Handled to true in OnKeyPress, the box's text is still set to the invalid value.

How do I prevent a keypress from updating a MaskedTextBox's text?

UPDATE: MaskedTextBox not TextBox. I don't think that should make a difference, but from the number of people telling me that e.Handled should work, perhaps it does.

+4  A: 

This will not type character 'x' in textbox1.

    char mychar='x'; // your particular character
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == mychar)
            e.Handled = true;
    }

EDIT: It works for MaskedTextBox as well.

HTH

nils_gate
That's what I'm doing. Perhaps it isn't working because it's a MaskedTextBox?
Simon
It works for MaskedTextBox as well. edited.
nils_gate
Post ur code dude..:)
nils_gate
A: 

The KeyPress should do it; are you doing this at the form? or at the control? For example:

static void Main() {
    TextBox tb = new TextBox();
    tb.KeyPress += (s, a) =>
    {
        string txt = tb.Text;
        if (char.IsLetterOrDigit(a.KeyChar)
            && txt.Length > 0 &&
            a.KeyChar <= txt[txt.Length-1])
        {
            a.Handled = true;
        }
    };
    Form form = new Form();
    form.Controls.Add(tb);
    Application.Run(form);
}

(only allows "ascending" characters)

Note that this won't protect you from copy/paste - you might have to look at TextChanged and/or Validate as well.

Marc Gravell
I'm doing it at the control.
Simon
A: 

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx Might help, the KeyDown event?

xan