文本框的价格/现金/货币在C# [英] Textbox for price/cash/currency on C#
问题描述
我有一个困扰了我一段时间的一个问题。我尝试了一些解决方案,但他们并没有奏效。
I have a problem that is haunting me for a while. I tried some solutions but they didn't worked.
我有一个文本框是现金输入(999,99 $例如)。然而,我需要自动输入,和。正确显示值。
I have a textbox that is for cash input ($999,99 for example). However I need to automatically input the "," and "." to display the value correctly.
我尝试了两种解决方案。其中之一是这样的:
I tried two solutions. One of them is this:
private void tx_ValorUnidade_TextChanged(object sender, EventArgs e)
{
string value = tx_ValorUnidade.Text.Replace(",", "").Replace("R$", "");
decimal ul;
//Check we are indeed handling a number
if (decimal.TryParse(value, out ul))
{
//Unsub the event so we don't enter a loop
tx_ValorUnidade.TextChanged -= tx_ValorUnidade_TextChanged;
//Format the text as currency
tx_ValorUnidade.Text = string.Format(System.Globalization.CultureInfo.CreateSpecificCulture("pt-BR"), "{0:C2}", ul);
tx_ValorUnidade.TextChanged += tx_ValorUnidade_TextChanged;
}
}
结果,但是,是很奇怪的。话可能无法在这一个,所以我录一个视频: http://www.screenr.com/2sLH
另一种是这样的:
private void tx_ValorUnidade_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(tx_ValorUnidade.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(tx_ValorUnidade.Text, System.Globalization.NumberStyles.AllowThousands);
tx_ValorUnidade.Text = String.Format(culture, "{0:N0}", valueBefore);
tx_ValorUnidade.Select(tx_ValorUnidade.Text.Length, 0); *
}
}
这一次有点儿工作,但有一个问题:如果用户想要插入somethink像10,00 $它不能。它也经过5个号码崩溃。视频到: http://www.screenr.com/1sLH
For original reference, I got the 2 codes from other questions here.
我怎样才能解决这个问题?我使用的例子错了吗?任何想法是值得欢迎的。
How can I fix it? Am I using the examples wrong? Any thought is welcome.
推荐答案
我想格式化时,你会好起来的,当用户移动到下一个控件,例如如下图所示。
I think you will be better off when formatting when the user moves to the next control, e.g. like below. Otherwise it will be very confusing as the text will change itself as the user is typing:
private void textBox1_Leave(object sender, EventArgs e)
{
Double value;
if (Double.TryParse(textBox1.Text, out value))
textBox1.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C2}", value);
else
textBox1.Text = String.Empty;
}
这篇关于文本框的价格/现金/货币在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!