tags:

views:

195

answers:

2

The question is simple: how to do it? I've a couple of MaskedTextboxes which are filled by some indirect user actions (so not by typing in values directly). The text within the textboxes is colored red when the input is being rejected by the mask. Fine so far.

However, I don't want the end-user to be able to edit the boxes directly. So, I added the following code:

    private void HandleMaskedTextBoxKeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = true;
    }

    private void HandleMaskedTextBoxKeyDown(object sender, KeyEventArgs e)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;
    }

And while most characters are handled, the backspace and delete keys aren't: text disappears when pressing those keys. How can those keys be handled, too?

(Another option would be to set the readonly property of the boxes to true, but then the text doesn't get colored red anymore when input is rejected. I tried to force the red color in the MaskInputRejected event, but this didn't work out, either.)

A: 

You can use a richtextbox. Set read only to true, and mask the chars with the code beind.

I hope that helps. RG

RG
+1  A: 

I think it's a good idea to set the MaskedTextBox's ReadOnly property to true. But instead of handling the MaskInputRejected event, you should use the TypeValidationCompleted event like this:

private void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e) {
  maskedTextBox1.ForeColor = e.IsValidInput ? Color.Black : Color.Red;
}

Since I guess you're modifying the value of the MaskedTextBox by code, you'll have to also handle the TextChanged event to trigger a validation like this:

private void maskedTextBox1_TextChanged(object sender, EventArgs e) {
  maskedTextBox1.ValidateText();
}

Finally (and this is key), since the MaskedTextBox will be read only, you'll want to set the BackColor and ForeColor properties back to Color.White and Color.Black respectively, but you'll have to do it in code, in the constructor of the form for instance...

maskedTextBox1.BackColor = Color.White;
maskedTextBox1.ForeColor = Color.Black;

If you have a lot of them, I suggest you create a new control that inherits from MasketTextBox and override those values.

Julien Poulin
Interesting solution, however, the maskedTextBox1_TypeValidationCompleted isn't fired after maskedTextBox1.ValidateText(), so the color still doesn't get red.
dbaw
Actually, it does (I took a look at it using Reflector), did set the BackColor to Color.White? Because it is true that it doesn't work if you don't do that... As to why, I have no idea!
Julien Poulin
I had to set the ValidatingType property on the textbox. It works now! Thanks.
dbaw