Display Currency Values with a Custom Control

This article shall describe the construction of a custom control used to display currency values. The control is intended for use in Win Forms application development.


Introduction

This article shall describe the construction of a custom control used to display currency values. The control is intended for use in Win Forms application development. The purpose of control is to allow the user to enter numeric values which are subsequently converted to and displayed as currency (as is indicated in figure 1 (below)).

The user of the control may drop any number of the currency controls into a form to display numeric values as currency; the control itself is merely an extended textbox.  By placing the code necessary to support the functionality into the format of a custom control, the need for writing the code necessary to support the display of currency for each textbox used is eliminated.

Image1.gif

Figure 1:  The Currency Control in Use
 

Getting Started

The solution contains two projects. The first project is called "CurrencyControlTest" and the second project is called "CurrencyTextBox". The first project is provided to demonstrate use of the control in a Win Forms application. The second project contains the actual custom control which is called "CurrencyTextBox".  

Image2.gif

Figure 2:  Solution Explorer with Both Projects Visible

The Custom Control Project

Code:  Currency Text Box

The custom control's code contains all of the necessary methods used to restrict user input and to display the values into a textbox as a currency value. The control contains only the default imports as shown in the following:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms; 

 

namespace CurrencyTextBox

Following the using statements and the namespace declaration, the class is configured to inherit from the standard textbox control. By inheriting from the textbox control, all of the functionality of the control is included. After declaring the class, the next section of code is used to declare a private member variable which, through a public property, is used to store the current dollar value. Maintaining the dollar value as an internal variable is necessary to support edits to the underlying value after the value has been converted to a formatted string. It further allows the user to perform calculations against this value when, for example, the contents of multiple controls are added together. 

/// <summary>

/// Extended Textbox Control used to display Currency

/// </summary>

public partial class CurrencyTextBox : TextBox

{

    // member variable used to keep dollar value

    private Decimal mDollarValue;

 

    // constructor

    public CurrencyTextBox()

    {

        InitializeComponent();

        DollarValue = 0;

    }

       

    // default OnPaint

    protected override void OnPaint(PaintEventArgs pe)

    {

        // Calling the base class OnPaint

        base.OnPaint(pe);

    }
}
 

The next section of code in the control is used to handle the keypress event. The purpose of the keypress event handler is to limit the user to keying in numbers and decimal points. The handler also allows the users to use the backspace button and other control characters when editing the contents of the currency text box. This code also limits the user to entering in only a single decimal point.

/// <summary>

/// Keypress handler used to restrict user input

/// to numbers and control characters

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void CurrencyTextBox_KeyPress(object sender, KeyPressEventArgs e)

{

    // allows only numbers, decimals and control characters

    if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.')

    {

        e.Handled = true;

    }

 

    if (e.KeyChar == '.' && this.Text.Contains("."))

    {

        e.Handled = true;

    }

 

    if (e.KeyChar == '.' && this.Text.Length < 1)

    {

        e.Handled = true;

    }

} 

After the keypress event handler, the next section of code is used to handle the "validated" event for the control. This handler will attempt to convert the contents of the textbox to a properly formatted currency value. 

/// <summary>
/// Update display to show decimal as currency
/// whenver it is validated
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CurrencyTextBox_Validated(object sender, EventArgs e)
{
    try
    {
        // format the value as currency
        Decimal dTmp = Convert.ToDecimal(this.Text);
        this.Text = dTmp.ToString("C");
    }
    catch { }
} 

Next up is the  code used to handle the control's click event. In the case of this control, the intent is to convert the value displayed in the textbox back to the actual underlying control value as it stored in control (the actual decimal value). If the current dollar value property is zero, the application will clear the textbox (so that the user does not end up with the cursor trailing the zero). If the dollar value property does contain a value, the cursor is positioned at the end of that value.

/// <summary>

/// Revert back to the display of numbers only

/// whenever the user clicks in the box for

/// editing purposes

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void CurrencyTextBox_Click(object sender, EventArgs e)

{

    this.Text = mDollarValue.ToString(); 

    if (this.Text == "0")

        this.Clear(); 

    this.SelectionStart = this.Text.Length;

} 

The next section of code after the click event handler is the code used to handle the text changed event for the control. In this instance, whenever the value in the control is changed, the dollar value property is updated to hold the latest value.

/// <summary>

/// Update the dollar value each time the value is changed

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void CurrencyTextBox_TextChanged(object sender, EventArgs e)

{

    try

    {

        DollarValue = Convert.ToDecimal(this.Text);

    }

    catch { }

} 

The last bit of code in the control implements the dollar value property.

/// <summary>

/// property to maintain value of control

/// </summary>

public decimal DollarValue

{

    get

    {

        return mDollarValue;

    }

    set

    {

        mDollarValue = value;

    }

}

Code:  Currency Control Test

This project is used to test the custom control. The project contains a single Windows form. The form contains three of the custom controls and a button. The button is used add up the values contained in the first and second controls and to then display the sum of the two values in the third control.

The code for this form is as follows:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace CurrencyControlTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        } 

  

        private void btnAdd_Click(object sender, EventArgs e)

        {

            decimal dTmp = currencyTextBox1.DollarValue +

currencyTextBox2.DollarValue;

            currencyTextBox3.Text = dTmp.ToString("C");

        }

    }

} 

Aside from the button click event handler, there was no additional code added to the form. The button click event handler adds the dollar value properties from the first and second controls. The sum of the two controls is displayed as currency in the third control. It is not really necessary to format the text here but it does make the conversion to a currency formatted string happen immediately. If this were not done, the value would display as a simple decimal value until the user tabbed away from the control or selected something else. 

Summary.

This article was intended to demonstrate an approach to building a custom control that could be used to display a decimal value as currency. By incorporating the code necessary to support the display of a decimal value in the format of currency into a custom control, the user may add any number of currency controls to a form without rewriting the code contained in the custom control for each instance of the control.