Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#
Tip/Trick

Currency TextBox .NET

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
5 Feb 2014CPOL1 min read 26.1K   875   6   8
This tip describes how to display the value as currency text, formatted in accordance with the current culture.

Introduction

This tip describes how to display the value as currency text, formatted in accordance with the current culture. MaskedTextBox control is inadequate about this concept. CurrencyTextBox is usercontrol.

Image 1

Background

I thought of a simple accounting program coding. I decided using MaskedTextBox because it has mask. But I had a new problem. MaskedTextBox control has inadequate and limited input number. I decided to create my own control.

Image 2

Using the Code

CurrencyTextBox is derived from TextBox control. This usercontrol is using via OnEnter and OnLeave events. You enter input numbers then after leave from CurrencyTextBox, it seems masked for currency. If you want to enter the same control again, it seems no-masked.

Usage Text and TextNoFormatting properties:
For example: if you enter 12345;

Region currencyTextBox.Text currencyTextBox.TextNoFormatting
USA (en-US)$12.345,00 12345,00
Turkey (tr-TR)12.345,00 TL12345,00

C#
/*
 * Author: emarti, Murat Özdemir
 * Date: 5 Feb 2014, v1.0 
 * Updated: 8 Feb 2014, v1.1 (Thanks to johannesnestler from CodeProject.com)
 */
using System;
using System.Linq;
using System.Windows.Forms;
using System.Globalization;

namespace CurrencyTextBox
{
    public partial class CurrencyTextBox: TextBox
    {
        readonly CultureInfo _ci = CultureInfo.InstalledUICulture;
        private readonly string _allowedCharacterSet;
        private readonly char _decimalSeparator;

        public CurrencyTextBox()
        {
            var nf = new CultureInfo(_ci.Name, false).NumberFormat;
            _decimalSeparator = nf.CurrencyDecimalSeparator.ToCharArray()[0];
            _allowedCharacterSet = string.Format("0123456789{0}", _decimalSeparator);
            
            InitializeComponent();
        }

        /// <summary>
        /// Return Currency Text with No Formatting
        /// </summary>
        public string TextNoFormatting
        {
            get { return TypedText(); }
        }

        protected override void OnLeave(EventArgs e)
        {
            double amount;
            Text = Double.TryParse(Text, NumberStyles.Currency, null, 
            out amount) ? amount.ToString("C") : 0.ToString("C");
            base.OnLeave(e);
        }

        private string TypedText()
        {
            var sonuc = string.Empty;
            return Text.Trim().Where(ch => _allowedCharacterSet.Contains(ch)).Aggregate
            (sonuc, (current, ch) => current + ch);
        }

        protected override void OnEnter(EventArgs e)
        {     
            Text = TypedText();
            base.OnEnter(e);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && 
            e.KeyChar != _decimalSeparator && !char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
            base.OnKeyPress(e);
        }
    }
}

Using the Control

CurrencyTextBox is a user control that you can add to your form. It behaves the same as a regular TextBox.

To use the control:

  • Right-click on your toolbox in Design view.
  • Click Browse. Navigate to CurrencyTextBox.dll. Hit OK.
  • Other alternative; add reference your project.
  • Add the control to your form.  
  • Enjoy!

History  

  • Version 1.0, Created 5 Feb 2014
  • Version 1.1 Created 8 Feb 2014
    • Code optimized
    • Added OnKeyPress Event, allowed to input (enter) numbers and decimal separator character only
    • Changed property syntax from 'Text_NoFormatting' to 'TextNoFormatting'  

License

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


Written By
Turkey Turkey
My name is Murat Özdemir. I'm a Turkish Dentist and living in Eskişehir (Turkey).
Software programming is one of my hobbies since 1990 and I like to deal with 1 and 0.
Do not forget to brush your teeth for your health. Smile | :)
Visit my homepage at http://emarti.sf.net

Comments and Discussions

 
Questiona Little better Pin
johannesnestler7-Feb-14 0:14
johannesnestler7-Feb-14 0:14 
AnswerRe: a Little better Pin
emarti7-Feb-14 5:09
emarti7-Feb-14 5:09 
AnswerRe: a Little better Pin
emarti7-Feb-14 6:30
emarti7-Feb-14 6:30 
GeneralRe: a Little better Pin
johannesnestler7-Feb-14 9:09
johannesnestler7-Feb-14 9:09 
GeneralRe: a Little better Pin
emarti8-Feb-14 1:38
emarti8-Feb-14 1:38 
I updated this. If you may analyze, I will be happy. Thank you again for showing me the way.
Divinum est sedare dolorem

GeneralMy vote of 2 Pin
johannesnestler7-Feb-14 0:03
johannesnestler7-Feb-14 0:03 
GeneralRe: My vote of 2 Pin
emarti7-Feb-14 5:06
emarti7-Feb-14 5:06 
GeneralRe: My vote of 2 Pin
johannesnestler7-Feb-14 9:15
johannesnestler7-Feb-14 9:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.