【发布时间】:2021-11-02 02:15:52
【问题描述】:
我有一个带有LostFocus 事件处理程序的TextBox,它调用一个将TextBox 中的数字字符串格式化为数字格式的方法。例如,123456,78 返回123 456,78。
如果我改为以123 45 开头,它会正确返回12 345,00。
但是,如果我先输入123456,78,它正确返回123 456,78,然后用退格键删除TextBox中的最后四个字符,即我通过单击退格键四次删除6,78,不是在职的。它只是将 123 45 保留在 TextBox 中。
但是,如果我选择 TextBox 中的所有文本并粘贴 123 45,它会正确返回 12 345,00。
当我一次单步调试时,我看到方法参数amountIn 正确存储了字符串123 45,无论是在我使用退格键还是选择和粘贴时。但是,Regex.IsMatch() 在我使用退格键时返回 false,在我选择和粘贴时返回 true。因此,我相信退格会在字符串中留下某种在调试时不可见但被IsMatch() 方法识别的工件。这是我的方法:
private void txtAmount_LostFocus(object sender, EventArgs e)
{
txtAmount.Text = ReformatAmount(txtAmount.Text);
}
public static string ReformatAmount(string amountIn)
{
string amountOut;
if (Regex.IsMatch(amountIn, @"^[0-9 ,.]+$"))
{
amountOut = Regex.Replace(amountIn, "[. ]", "");
amountOut = Convert.ToDecimal(amountOut).ToString("N");
return amountOut;
}
else
{
amountOut = amountIn;
return amountOut;
}
}
【问题讨论】:
-
您是否考虑过改用
decimal.TryParse之类的东西? -
飞狗,我试过你的方法,效果也不错。一个巧妙的解决方案!谢谢