C# 从右向左设置MaskedTextBox值
我现在的面具是#9.99 #表示“+”或“-”符号 当我设置屏蔽文本框的值时,如果该值为负值,它将为我提供正确的值 但是,当值为正值时,它给出了错误的答案 下面是测试它的实际代码。 例如 我需要它是\u 0.14 从RightToLeft设置属性无效,因为我不希望用户从右向左键入C# 从右向左设置MaskedTextBox值,c#,winforms,maskedtextbox,C#,Winforms,Maskedtextbox,我现在的面具是#9.99 #表示“+”或“-”符号 当我设置屏蔽文本框的值时,如果该值为负值,它将为我提供正确的值 但是,当值为正值时,它给出了错误的答案 下面是测试它的实际代码。 例如 我需要它是\u 0.14 从RightToLeft设置属性无效,因为我不希望用户从右向左键入 非常感谢您的帮助。我想您需要填充空间: maskedTextBox2.Text = value2.ToString().Length < maskedTextBox2.Mask.Length ?
非常感谢您的帮助。我想您需要填充空间:
maskedTextBox2.Text = value2.ToString().Length < maskedTextBox2.Mask.Length ?
value2.ToString().PadLeft(maskedTextBox2.Mask.Length,' '): value2.ToString();
请注意,您必须检查
值是否有小数点。上面的代码没有这样的检查。如果您输入双值=25
,它将爆炸。您可能还需要处理其他边缘情况。直接设置文本
不起作用,因为掩码将决定文本的显示方式0.14
将首先变为014
(因为该点将被忽略),然后014
将在从Mask
应用格式后变为01.4
。如果您想直接设置文本
,您可能需要创建自己的MaskedTextBox
,虽然这很简单,但我想给您一个解决方案,我们使用扩展方法
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
如果值为正数,您希望在它前面有一个+
符号吗?我希望它显示为0.14,或者在前面有一个正数都可以。您使用的是哪种遮罩文本框
?因为标准的没有值
属性。请再看一次问题,我已经编辑了它。问题是,如果我在掩码中添加一个额外的小数位,即从#9.99到#9.999,结果将是#0.014,而不是0.14。在这种情况下,您将需要确定小数点后的位数,并在右侧填充0,而对于小数点前的位数,则必须在右侧填充空格左边请参阅我编辑的答案。
// 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;
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