C# - CPF Mask

Asked

Viewed 446 times

3

I’m looking to put a placeholder effect on a masking text box.

The idea is to activate the CPF mask as soon as it enters the text box and disable it if the text box is empty when exiting.

private void mskCpf_Enter(object sender, EventArgs e)
    {
        mskCpf.Text = "";
        mskCpf.Mask = "999\.999\.999-99";
    }

In this code it does not recognize the backslash and so does not work this way

1 answer

3


The contrary method of Enter is the Leave. Leave is thrown when the control loses focus, Enter, is thrown when a control gains focus.

You can associate this with this event without needing to create a dedicated method just to display or hide the mask:

maskedTextBox1.Enter += (object enterSender, EventArgs enterArgs) => { maskedTextBox1.Mask = @"999\.999\.999-99"; };
maskedTextBox1.Leave += (object leaveSender, EventArgs leaveArgs) => { maskedTextBox1.Mask = ""; };

Add these two lines to the Form startup and you’re all set.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.