Parsing Text from a Masked Text Box - c#

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?

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);

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

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
}

Related

C# display / (forward slash) in MaskedTextBox

I noticed that when the mask defined for input in a MaskedTextBox contains "/", it is automatically substituted by "-" in the textbox.
I tried this using the default Date format available in VS, which in the form's Designer results in the following code
this.maskedTextBox2.Name = "maskedTextBox2";
this.maskedTextBox2.Mask = "00/00/0000";
this.maskedTextBox2.ValidatingType = typeof(System.DateTime);
and also for another MaskedTextBox by defining my custom mask in the form's constructor like this
InitializeComponent();
this.maskedTextBox1.Mask = #"00/00/0000";
In both cases the prompt displayed in the text boxes looks like this
__-__-____
Is there a way to actually display slashes there, instead of dashes?
Marek
According to this page, a slash is a 'date separator' and therefore I'm guessing that your system currently runs in a locale where a date separator is a dash.
/ Date separator. The actual display character used will be the date symbol appropriate to the format provider, as determined by the control's FormatProvider property.
If you really DO want a forward slash then "00\/00\/00" should do the trick (but then it's not really a compliant date input).

C# format to thousand seperator

I am trying to format user input to a thousand seperator format. I tried the code here, but it keeps breaking the application:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDouble(Amt));
So when the user inputs 3566412, then it needs to convert automatically to 3,566,412
You are trying to convert the control (named Amt) to a double, which is a bad idea since you want to convert the text of the control (Amt.Text). I would suggest to use a decimal since that is more precise and will not cause floating point issues:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDecimal(Amt.Text));
Another thing to consider is to use a control that can mask itself, so you don't need to replace the text yourself every time.
You might want to check out Standard Numeric Format Strings at MSDN
Then you could do something like
Amt.Text = inputnumber.ToString("N");
Which will format 3566412 to 3,566,412.0
If you want to take it directly from the textbox, you could do something like this, which checks if the text can be parsed before setting the text
double result = 0;
if (double.TryParse(Amt.Text, out result)
{
Amt.Text = result.ToString("N");
}

Formatting textbox c# and using it unformatted value

I´m using some textboxes to show totals, subtotals and discounts. I´m converting decimals to string to represent them in the textbox. Also, I would like to have the "$" at the beginning.
I have achieved this by using this:
tbx_total.Text = total.ToString("$ ##0.##");
Graphically, this is working great, but my big problem is that I need that textbox value to calculate other ones. Basically, I get a formatting error during runtime when I try to convert that textbox text to decimal. Obviously, this is due to the ToString("$ ##0.##") format. Is there any way to get the value without the format?
One simple solution will be:
tbx_total.Text = total.ToString("$ ##0.##");
tbx_total.Tag = total;
Then use tbx_total.Tag property for further usage.
When reading it back in you can parse with NumberStyles to get your desired effect. There is a number of bit-wise operations on NumberStyles so I suggest researching how to use them for more flexibility:
double.Parse(total, NumberStyles.Currency);
Also I tend to like this for formatting currency a bit more but purely stylistic.
String.Format("{0:C}", total);
Note: Parsing back and forth does incur some overhead so depending on the amount of data it may be more wise to offload the value to an object and reference that when you need the decimal value again.
As an alternative, you can do this, whenever you read the value:
double value = 0;
if (!double.TryParse(tbx_total.Text.TrimStart(new char[] { '$', ' ' }), out value))
{
//Ooops... not a valid number
}
So here you basically remove the added '$' and space before the number enabling you to parse it as a double. This way you can check if the number has been entered correctly (provided that the user can edit the textbox.
I think you should store your original values (decimal) in a DataTable or some other collection and use these values to calculate what you need.
So you can format decimal values in any format you like without warry about how to convert back from strings.

What is the best way to format an edit box that represents a numeric value?

In my c# program I have a very simple DevExpress edit box that represents a numeric value.
What I would like to do is to add a restriction on the number of decimals in such a way that:
Users cannot type, paste or in any other way enter a value that contains more than a predefined number of decimals. I fact I just want to editbox to ignore the user's typing as soon as 3 decimals have been entered.
If a programmer sets the edit box' text, the value is rounded so that it meets the requirements.
What is the best way to do this?
Ps.: I thought this would solve my problem:
valueTextEdit.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
valueTextEdit.Properties.DisplayFormat.FormatString = "#.000;[#.000];0.000";
But it doesn't seem to do anything. I can still enter values with 10 decimals. Also in code I can set the edit box text to a value with a larger number of decimals.
You need to set the UseMaskAsDisplayFormat = true:
Have a look here and here
EDIT:
Nice example here
try this
MaskTextBox control of .Net
you can use MaskedTextBox for entering data in numeric format in text box.
i hope this will help you
thank you
You can build your own class that derives (inherits) from TextBox, then override property Text to add your requirments:
internal class SmartTextBox : TextBox
{
public SmartTextBox()
{
}
public override string Text
{
get
{
return base.Text;
}
set
{
// validate 'value' before setting it
base.Text = value;
}
}
}
After you build your project, you will find your new Control called SmartTextBox with .NET Controls.
EDIT: However, if you use TextBox for numeric input only, why don't you use NumericUpDown Control? It is much better, users can not input characters and you can even set the precision of decimal number.

C# Windows form text box format with data binding

I have a windows form with a text box: txtMyText.
txtMyText.Text is Bound to a data source: long lMyLongValue.
On the form I would like the value to display as a six digit value with leading zeros. Example 000123.
How can this be accomplished?
I believe Binding.Format event, can be pretty suitable for your needs, if not, you can bind it not to long property, but to string property and handle conversion from long -> srtring and vice versa "by hand".
for convert it into formatted string use pretty simple example:
long l =13;
string sformat = l.ToString("000000"); // 000013
Regards.
Yes, follow link
How to: Pad a Number with Leading Zeros

Categories