C#上价格/现金/货币的文本框 [英] Textbox for price/cash/currency on C#

查看:23
本文介绍了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#上价格/现金/货币的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆