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

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.


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


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.


http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx可能帮助,KeyDown事件?

链接地址: http://www.djcxy.com/p/95958.html

上一篇: 如何使文本框只接受字母字符

下一篇: 如何防止按键更新MaskedTextBox的文本?