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.
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.
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 TL | 12345,00 |
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();
}
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
'