Search code examples
c#winformsmaskedtextbox

Remove extra _ from mask


Both that inputs are valid:

(00)0000-0000
(00)10000-0000

so I'm using this mask:

(00)90000-0000

as one of the digits after (00) is optional it can have either 8 or 9 digits. But if the input has 8 digits, the MaskTextBox show an extra _ in the end, like this (00)0000-0000_ but as that's of the optional digit, I'd like to remove it. If it has 8 or 9 digits must be show as (00)0000-0000 or (00)00000-0000 respectively. I hope it's clear


Solution

  • Try using the TextChanged event to change the PropmtChar property according to the MaskCompleted property:

    private void MaskedTextBox1_TextChanged(object sender, EventArgs e)
    {
        MaskedTextBox1.PromptChar = (MaskedTextBox1.MaskCompleted) ? ' ' : '_' ;
    }