ARTICLE

Display Currency Values with a Custom Control

Posted by Scott Lysle Articles | Windows Controls August 02, 2007
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.
Download Files:
 
Reader Level:

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

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.



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 that is called "CurrencyTextBox". 



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:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Data

Imports System.Drawing

Imports System.Text

Imports System.Windows.Forms

 

Namespace CurrencyTestbox

 

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

          Inherits TextBox

          ' member variable used to keep dollar value

          Private mDollarValue As Decimal

          ' constructor

          Public Sub New()

                   InitializeComponent()

                   DollarValue = 0

          End Sub

 

          ' default OnPaint

          Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)

                   ' Calling the base class OnPaint

                   MyBase.OnPaint(pe)

          End Sub

End Class

 

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 Sub CurrencyTextBox_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

          ' allows only numbers, decimals and control characters

          If (Not Char.IsDigit(e.KeyChar)) AndAlso (Not Char.IsControl(e.KeyChar)) AndAlso e.KeyChar <> "."c Then

                   e.Handled = True

          End If

 

          If e.KeyChar = "."c AndAlso Me.Text.Contains(".") Then

                   e.Handled = True

          End If

 

          If e.KeyChar = "."c AndAlso Me.Text.Length < 1 Then

                   e.Handled = True

          End If

End Sub

 

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 Sub CurrencyTextBox_Validated(ByVal sender As Object, ByVal e As EventArgs)

          Try

                   ' format the value as currency

                   Dim dTmp As Decimal = Convert.ToDecimal(Me.Text)

                   Me.Text = dTmp.ToString("C")

          Catch

          End Try

End Sub

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 Sub CurrencyTextBox_Click(ByVal sender As Object, ByVal e As EventArgs)

          Me.Text = mDollarValue.ToString()

          If Me.Text = "0" Then

                   Me.Clear()

          End If

          Me.SelectionStart = Me.Text.Length

End Sub

 

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 Sub CurrencyTextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)

          Try

                   DollarValue = Convert.ToDecimal(Me.Text)

          Catch

          End Try

End Sub

 

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

''' <summary>

''' property to maintain value of control

''' </summary>

Public Property DollarValue() As Decimal

          Get

                   Return mDollarValue

          End Get

 

          Set(ByVal value As Decimal)

                   mDollarValue = value

          End Set

End Property

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:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Data

Imports System.Drawing

Imports System.Text

Imports System.Windows.Forms

 

Namespace CurrencyControlTest

          Public Partial Class Form1

                   Inherits Form

                   Public Sub New()

                             InitializeComponent()

                   End Sub

 

                   Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)

                             Dim dTmp As Decimal = currencyTextBox1.DollarValue + currencyTextBox2.DollarValue

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

                   End Sub

          End Class

End Namespace

 

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.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/). 

Login to add your contents and source code to this article
share this article :
post comment
 

True, it is formatting it as currency when you exit the textbox, not on the fly.

Posted by Scott Lysle Nov 05, 2008

The control works great! However, if I set the dollar amount either in the Properties or programatically it really doesn't show until you click on the control. I cannot find a way to programatically "click the control. Can you provide and example on how to do this? Thanks! Example CurrencyTextBox_BG1.DollarValue = "$15,200.00" sets the value but it doesn't show the value until you click DollarValue property doesn't show until you click the control.

Posted by Pablo Santa Oct 27, 2008
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor