Parsing Text from a Masked Text Box

1.8k views Asked by At

I have a WinForms application written in C#

I have until recently many textboxes on my forms where the user inputs financial amounts. I have not incorporated any form of mask initially and whenever I need to work with the values input by the users I would Parse the text from each box into Decimal values with Decimal.Parse;

However I have been asked to make the textboxes look like financial amounts i.e. £1,050.75 rather than 1050.75 I therefore started to change the textboxes into MaskedTextBox and gave them a Mask of £#,##0.00 However now each attempt to Parse the text from the MaskedTextBoxes gives an error 'Input string not in the correct format'.

How do I obtain the users input from the MaskedTextBox and parse into decimal format to work with?

Should I be using MaskedTextBox at all, or is there another way of showing a financial type formatting on the form, without effecting the Decimal.Parse method?

3

There are 3 answers

0
Learner On BEST ANSWER

When you are getting the value from Maskedtextbox, it is taking the value as £#,##0.00 . so the symbol will not be converted to decimal. Try to remove the symbol and convert the value to decimal. like

        string val= maskedTextBox1.Text.Replace("£","");
        Decimal.Parse(val);
0
Sinatr On

You can check MaskFull to see if text is properly enter and then apply anti-mask (by removing that, what your mask is adding).

Unfortunately, I am not aware about automated unmasking. But you can do something like:

if(maskedTextBox1.Mask)
{
    var enteredText = maskedTextBox1.SubString(1).Replace(",", null); // remove pound symbol and commas
    // ... parse as with normal TextBox
}
0
user1318499 On

You can use a format option with AllowCurrencySymbol. It has to match the currency symbol of the culture. This code I converted from VB so I hope it's correct.

Application.CurrentCulture = New Globalization.CultureInfo("en-GB");
Decimal.Parse("£12,345.67", Globalization.NumberStyles.AllowThousands | Globalization.NumberStyles.AllowDecimalPoint | Globalization.NumberStyles.AllowCurrencySymbol);

Also, see this question if you don't want to change the culture: Problem parsing currency text to decimal type