Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

string - 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.

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;
        }
    }

The result, however, is very weird.

The other one is this:

    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); *
          }
    }

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some people might want to actually format a textbox as they type. So this is my solution if anyone is looking for one.

It actually assumes you are entering one digit at a time so therefore as you press "1" it assumes "$0.01" and when they press "2" it then assumes "$0.12" and so on and so forth.

I could not find anything online about formatting as they typed. It has been tested and if any errors let me know.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    //Remove previous formatting, or the decimal check will fail including leading zeros
    string value = textBox1.Text.Replace(",", "")
        .Replace("$", "").Replace(".", "").TrimStart('0');
    decimal ul;
    //Check we are indeed handling a number
    if (decimal.TryParse(value, out ul))
    {
        ul /= 100;
        //Unsub the event so we don't enter a loop
        textBox1.TextChanged -= textBox1_TextChanged;
        //Format the text as currency
        textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
        textBox1.TextChanged += textBox1_TextChanged;
        textBox1.Select(textBox1.Text.Length, 0);
    }
    bool goodToGo = TextisValid(textBox1.Text);
    enterButton.Enabled = goodToGo;
    if (!goodToGo)
    {
        textBox1.Text = "$0.00";
        textBox1.Select(textBox1.Text.Length, 0);
    }
}

private bool TextisValid(string text)
{
    Regex money = new Regex(@"^$(d{1,3}(,d{3})*|(d+))(.d{2})?$");
    return money.IsMatch(text);
}

To make it look nice I'd recommend starting the text box with the text $0.00 on the form load like so:

    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.Text = "$0.00";
        textBox1.SelectionStart = inputBox.Text.Length;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...