Textbox for price/cash/currency on C#(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;
}
}
然而,结果却很奇怪.
另一个是这样的:
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); *
}
}
这个有点工作,但有一个问题:如果用户想插入一些像 10,00 美元的东西,它不能.它也会在 5 个数字后崩溃.
This one kinda works, but there is a issue: if the user wants to insert somethink like $10,00 it can't. It also crashes after 5 numbers.
对于原始参考,我从 other 问题在这里.
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#上价格/现金/货币的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#上价格/现金/货币的文本框


- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01