Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
1.67/5 (3 votes)
See more:
Below is what I am trying to archive in C#.
I have a textbox that I will be using to enter an amount.

Current I am entering the full amount manually including the decimal e.g. “10.05”

What I want to achieve is to have a default value on the textbox of “0.00” such that if I press a number e.g. 55, the textbox automatically replaces the first 2 zeros of the default "0.00" value to display “0.55” without any manual interference from me.

If I enter 3355, it has to automatically get displayed as 33.55 real time as I am typing
Posted
Comments
DimitriStPi 15-Jan-16 9:13am    
Hi,
Can you tell us about the technology you use ?
WPF, WinForms ?
Thanks.
BillWoodruff 15-Jan-16 12:53pm    
are there any limits on how many digits/characters the user can type ?

1 solution

Hi,

Thank you for taking time to look into my problem. I have found the answer and it is below.

-----------------------

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;

namespace frmMain
{

    public partial class frmMain : Form
    {
        
        public frmMain()
        {
            InitializeComponent();
        }


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


        }

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

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

    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900