Reputation: 215
I currently have a mask of #9.99 The # is there for '+' or '-' sign.
When I set the value of the Masked text box, where the value is negative it will give me the correct value.
However when the value is positive it gives me the incorrect answer.
Here is actual code to test it out. Eg.
private void Form1_Load(object sender, EventArgs e){
double value = -0.14;
double value2 = 0.14;
maskedTextBox1.Text = value.ToString();
maskedTextBox2.Text = value2.ToString();
}
I need it to be _0.14
Setting the Property from RightToLeft does not work because I do not want the user to type from the right to left.
Any help is greatly appreciated.
Upvotes: 0
Views: 4033
Reputation: 63317
Setting Text
directly as you did doesn't work because the Mask
will determine how the text is display. 0.14
will become 014
first (because the dot will be ignored) and then 014
will become 01.4_
after applying format from Mask
. If you want to set the Text
directly, you may have to create your own MaskedTextBox
, although this is easy but I want to give you the solution in which we use an extension method
instead.
public static class MaskedTextBoxExtension {
public static void SetValue(this MaskedTextBox t, double value){
t.Text = value.ToString(value >= 0 ? " 0.00" : "-0.00");
}
}
//I recommend setting this property of your MaskedTextBox to true
yourMaskedTextBox.HidePromptOnLeave = true;//this will hide the prompt (which looks ugly to me) if the masked TextBox is not focused.
//use the code
yourMaskedTextBox.SetValue(0.14);// => _0.14
yourMaskedTextBox.SetValue(-0.14);// => -0.14
Upvotes: 1
Reputation: 3752
I think you will need to pad space:
maskedTextBox2.Text = value2.ToString().Length < maskedTextBox2.Mask.Length ?
value2.ToString().PadLeft(maskedTextBox2.Mask.Length,' '): value2.ToString();
Editing answer in response to OP's comment:
// Pad the left of decimal with spaces
string leftOfDecimal = value.ToString().Split('.')[0].PadLeft(maskedTextBox1.Mask.Split('.')[0].Length);
// Pad the right with 0s
string rightOfDecimal = value.ToString().Split('.')[1].PadRight(maskedTextBox1.Mask.Split('.')[1].Length,'0');
maskedTextBox1.Text = leftOfDecimal + "." + rightOfDecimal;
Note that you will have to check if the value
has a decimal point or not. The code above has no such check. If you input double value = 25
, it will blow up. There might be other edge cases too that you will have to handle.
Upvotes: 1