How to remove mask from a Maskedtextbox

Asked

Viewed 1,937 times

1

I’m using Visual Studio to make an application using Windows Forms in C# and I need to get all the Maskedtextbox of the form, without masks.

I’m using the code below right now. The Maskedtexbox are obtained, but does not eliminate the masks to make the if. Does anyone have any suggestions?

foreach (Control c in ctrl.Controls)
            {
                 //Analisa os Maskedtextbox
                if (c is MaskedTextBox)
                {
                    ((MaskedTextBox)c).Text.Replace("/", "").Replace(",", "").Replace("-", "");

                    if ((((MaskedTextBox)c).Tag == "*") && (((MaskedTextBox)c).Text.Length<=4))
                    {
                        retorno = true;
                        ((MaskedTextBox)c).BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
                        MessageBox.Show(c.Text);

                    }
                    else
                        ((MaskedTextBox)c).BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
                }
}

1 answer

3


You can get the value of MaskedTextBox in two ways, depending on what you need:

Permanent

In your Maskedtextbox change the property value TextMaskFormat for ExcludePromptAndLiterals. This way you can use TextMaskFormat.Text (anywhere) and the value returned will be the text without the mask.

Temporary

If you need the value with the mask on other parts of the code and want to remove the mask only for the if can do the following:

maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
var valorSemMascara = maskedTextBox.Text;
maskedTextBox.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;

Note: None of the solutions changes the visual aspect of MaskedTextBox.

Example:

An example of the code you can use inside the one button event (tested in VS2013, . NET4.5):

private void button1_Click(object sender, EventArgs e)
{
    foreach (MaskedTextBox mtBox in Controls.OfType<MaskedTextBox>())
    {
        mtBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
        MessageBox.Show(mtBox.Text); // Troque esta parte pelas suas condições.
        mtBox.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;
    }
}
  • from an example please that your code did not work.....

Browser other questions tagged

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