C# display / (forward slash) in MaskedTextBox - c#

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

Related

Digit Grouping Symbol messes with number format

I have a WinForms application, in which I have a label, where I bind a decimal to. I have also added a .Format method to the binding. Like this:
// Add data binding for the lavel
Binding bindWithFormat = new Binding("Text", viewModel, nameof(viewModel.BindingNumber));
bindWithFormat .Format += viewModel.FormatAsNumber;
lblNumber.DataBindings.Add(bindWithFormat);
// Formatting function
public void FormatAsNumber(object sender, ConvertEventArgs e)
{
// The method converts only to string type. Test this using the DesiredType.
if (e.DesiredType != typeof(string)) return;
// Formats the value with thousand separator and zero decimals
e.Value = String.Format("{0:N0}", e.Value);
}
This works fine under normal circumstances, but if I choose a particular type of Digit Grouping Symbol, it looks like this (it is supposed to show "15 000 000"):
I first thought it was when I used a blank space (" ") as symbol, but when I explicitly type a blank space, then it shows it as intended. However, there is another symbol I can chose in the regional settings, which looks like a space, but it causes the above formatting error when selected (unlike when I explicitly type space):
What the heck is going on? According to this website, the symbol is "no break space" (U+00A0). So it is a space. But not a space. And for some reason, it seriously messes up the formatting. What to do?
Bonus info: After playing around some more, it seems to only affect that specific font, that I was using (it only exists in my company). If I change fonts to e.g. Segoe UI, then the problem disappears.

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

Parsing Text from a Masked Text Box

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
}

C# custom mask for textbox

I know there is masked textbox component for C#, but what I need is to create masked text box which requires entered text in format: LLL/LLL but when I enter such mask into Mask property in preview and mask I see separator "." but not "/" as I want to have. Any help?
Thanks
The / character is the date separator character in the mask. What you'll actually get depends on your culture preferences. To get a literal / you'll have to escape it with a \. Like this:
this.maskedTextBox1.Mask = #"LLL\/LLL";
Don't use the # when you use the Properties window.
Thanks for this clue
there is one more problem in maskedtextbox that is when the system short date changes the mask also changes for example..
Before
System date : d/M/yy
Mask Format : __/__/__
After
System date : d-M-yy
Mask Format : __-__-__
Using escape char hepled me.
Just add escape char in mask. For example:
textbox1.Mask = 00/\00/\00

C#: How do you go upon constructing a multi-lined string during design time?

How would I accomplish displaying a line as the one below in a console window by writing it into a variable during design time then just calling Console.WriteLine(sDescription) to display it?
Options:
-t Description of -t argument.
-b Description of -b argument.
If I understand your question right, what you need is the # sign in front of your string. This will make the compiler take in your string literally (including newlines etc)
In your case I would write the following:
String sDescription =
#"Options:
-t Description of -t argument.";
So far for your question (I hope), but I would suggest to just use several WriteLines.
The performance loss is next to nothing and it just is more adaptable.
You could work with a format string so you would go for this:
string formatString = "{0:10} {1}";
Console.WriteLine("Options:");
Console.WriteLine(formatString, "-t", "Description of -t argument.");
Console.WriteLine(formatString, "-b", "Description of -b argument.");
the formatstring makes sure your lines are formatted nicely without putting spaces manually and makes sure that if you ever want to make the format different you just need to do it in one place.
Console.Write("Options:\n\tSomething\t\tElse");
produces
Options:
Something Else
\n for next line, \t for tab, for more professional layouts try the field-width setting with format specifiers.
http://msdn.microsoft.com/en-us/library/txafckwd.aspx
If this is a /? screen, I tend to throw the text into a .txt file that I embed via a resx file. Then I just edit the txt file. This then gets exposed as a string property on the generated resx class.
If needed, I embed standard string.Format symbols into my txt for replacement.
Personally I'd normally just write three Console.WriteLine calls. I know that gives extra fluff, but it lines the text up appropriately and it guarantees that it'll use the right line terminator for whatever platform I'm running on. An alternative would be to use a verbatim string literal, but that will "fix" the line terminator at compile-time.
I know C# is mostly used on windows machines, but please, please, please try to write your code as platform neutral. Not all platforms have the same end of line character. To properly retrieve the end of line character for the currently executing platform you should use:
System.Environment.NewLine
Maybe I'm just anal because I am a former java programmer who ran apps on many platforms, but you never know what the platform of the future is.
The "best" answer depends on where the information you're displaying comes from.
If you want to hard code it, using an "#" string is very effective, though you'll find that getting it to display right plays merry hell with your code formatting.
For a more substantial piece of text (more than a couple of lines), embedding a text resources is good.
But, if you need to construct the string on the fly, say by looping over the commandline parameters supported by your application, then you should investigate both StringBuilder and Format Strings.
StringBuilder has methods like AppendFormat() that accept format strings, making it easy to build up lines of format.
Format Strings make it easy to combine multiple items together. Note that Format strings may be used to format things to a specific width.
To quote the MSDN page linked above:
Format Item Syntax
Each format item takes the following
form and consists of the following
components:
{index[,alignment][:formatString]}
The matching braces ("{" and "}") are
required.
Index Component
The mandatory index component, also
called a parameter specifier, is a
number starting from 0 that identifies
a corresponding item in the list of
objects ...
Alignment Component
The optional alignment component is a
signed integer indicating the
preferred formatted field width. If
the value of alignment is less than
the length of the formatted string,
alignment is ignored and the length of
the formatted string is used as the
field width. The formatted data in
the field is right-aligned if
alignment is positive and left-aligned
if alignment is negative. If padding
is necessary, white space is used. The
comma is required if alignment is
specified.
Format String Component
The optional formatString component is
a format string that is appropriate
for the type of object being formatted
...

Categories