Textbox for price/cash/currency on C#

前端 未结 6 552
慢半拍i
慢半拍i 2020-12-15 15:10

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). Howe

6条回答
  •  鱼传尺愫
    2020-12-15 15:31

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

提交回复
热议问题