I am trying to create custom control using Textbox to handle currency while my purpose is to display the currency symbol while writing in the textbox and when lost focus.
Imports System.Globalization
Public Class uc_txt_cur
Inherits TextBox
Property xCurrency$ = "US"
Property xDecimal As Integer = 2
Property xValue As String
Property xIntegerValue As Integer
Property xDoubleValue As Double
Private Sub InitializeComponent()
Me.SuspendLayout
Me.ResumeLayout(False)
End Sub
Sub New
Me.Text = "0.00 US"
Me.TextAlign = HorizontalAlignment.Right
End Sub
Private Sub txt_TextChanged(sender As Object, e As EventArgs) Handles me.TextChanged
Try
'Remove any previous formatting
Dim value As String = Me.Text.Replace(",", "").Replace("US", "").Replace(".", "").Replace(" ", "")
MsgBox(value)
'Convert the numeric string to a number and apply currency formatting
Me.Text = cdbl(value).ToString("N2") + " " + xCurrency
MsgBox(Me.Text)
Me.Select(Me.Text.Length, 0)
Catch ex As FormatException
'Handle invalid format gracefully if needed
Me.Text = ""
End Try
End Sub
Private Sub txt_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
If Char.IsDigit(e.KeyChar) OrElse Char.IsControl(e.KeyChar) Then
' Allow digit or control character input
'MyBase.OnKeyPress(e)
ElseIf e.KeyChar = "."c AndAlso Not Me.Text.Contains(".") Then
' Allow one decimal point if it doesn't already exist
'MyBase.OnKeyPress(e)
Else
' Ignore any other input (e.g., letters, symbols)
e.Handled = True
End If
End Sub
End Class
to My surprise when I place the control on the form on design time, the sub txt_TextChanged(sender As Object, e As EventArgs) is executed.
Is this normal to execute a sub at design time?
The error msg is
Failed to create component ‘uc_txt_cur’. The error message follows:
‘System.FormatException: Input string was not in a correct format.
at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat)’
Can someone help to make it work?