Link to home
Start Free TrialLog in
Avatar of jxharding
jxharding

asked on

i cannot get a textbox to have a mask, i need to enter a currency value only into textbox

what i need to do is when a user enters a value, only let numerical values be entered into the textbox
ATTEMPT1
i have tried a good few examples, on this site, there is some source code but i cannot download the project for some reason
http://www.codeproject.com/vb/net/cpflexmaskeditbox.asp

ATTEMPT2
another question in experts exchange told the user to register "Microsoft Masked Edit Control, version 6.0""
but now what?
i dont see an extra property in the textboxes now

ATTEMPT3
and then bobjohnson187@??????.com posted this code in a post , and i made a class out of it but i dont know what to do next
'---------------------------------------------------
Public Class TextBoxNumeric
    Inherits System.Windows.Forms.TextBox

#Region " Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        'This call is required by the Windows Form Designer.
        InitializeComponent()
        'Add any initialization after the InitializeComponent() call
    End Sub
    'UserControl1 overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        components = New System.ComponentModel.Container
    End Sub
#End Region

    Dim m_IntegerOnly As Boolean
    Dim m_PositiveOnly As Boolean
    '<Description("If TRUE, only integers can be entered."), _
    'Browsable(True), _
    'Category("Validation"), _
    'DefaultValue(False)> _
    Property IntegerOnly() As Boolean
        Get
            Return m_IntegerOnly
        End Get
        Set(ByVal Value As Boolean)
            m_IntegerOnly = Value
        End Set
    End Property
    '<Description("If TRUE, only positive numbers can be entered."), _
    'Browsable(True), _
    'Category("Validation"), _
    'DefaultValue(False)> _
    Property PositiveOnly() As Boolean
        Get
            Return m_PositiveOnly
        End Get
        Set(ByVal Value As Boolean)
            m_PositiveOnly = Value
        End Set
    End Property
    Private Sub NumericTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Dim KeyAscii As Integer
        KeyAscii = Asc(e.KeyChar) ' NOTE: used as a flag when = 0 to mark bad values
        Select Case KeyAscii
            Case 48 To 57, 8, 13 ' Digits 0 - 9, Backspace, CR.
                ' These are OK, so accept them.
            Case 45 ' Minus sign.
                If PositiveOnly Then
                    KeyAscii = 0
                Else
                    ' Number can have only one minus sign, so if
                    ' we already have one, throw this one away.
                    If InStr(Me.Text, "-") <> 0 Then
                        KeyAscii = 0
                    End If
                    ' If the insertion point is not sitting at zero
                    ' (i.e., the beginning of the field), throw away
                    ' the minus sign because it's not valid anywhere
                    ' but the first position
                    If Me.SelectionStart <> 0 Then
                        KeyAscii = 0
                    End If
                End If
            Case 46 ' Period (decimal point).
                If IntegerOnly Then
                    KeyAscii = 0
                Else
                    ' If we already have one period, throw it away
                    If InStr(Me.Text, ".") <> 0 Then
                        KeyAscii = 0
                    End If
                End If
            Case Else ' Provide no handling for other keys.
                KeyAscii = 0
        End Select
        ' If we want to throw the keystroke away, then set the event
        ' as already handled. Otherwise, let the keystroke be
        ' handled normally.
        If KeyAscii = 0 Then
            e.Handled = True
        Else
            e.Handled = False
        End If
    End Sub
'---------------------------------------------------
ATTEMPT4
http://www.c-sharpcorner.com/Download.asp?file=/Code/2004/Jan/MaskedTextBoxJP.zip
but this is in C# and im doing vb.net, maybe there is still a way to use it if someone can help me


personally i would like to get option 2 or 3 working

thank you
Avatar of iboutchkine
iboutchkine

Here are several examples for you

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
        If Char.IsDigit(e.KeyChar) Then
            MsgBox("Digit entered")
        End If
        'disable non-digits
        e.Handled = Not Char.IsDigit(e.KeyChar)
    End Sub

Be aware
that there are a couple potential problems with these solutions.

   - can't backspace to edit an entry
   - can't paste valid data with keyboard
   - can paste invalid data with mouse
   - can't copy data with keyboard
some thoughts
The text in the textbox should by validated in the validating event and
not when the user types the text. Preventing the user from entering
characters can be annoying, for example when entering a negative number
you should not prevent the user from entering more than one "-"
character. The user is responsible for the proper format, when the focus
is set to an other control, the content gets validated. You can use an
ErrorProvider control to make the user aware of malformed or invalid
input.

'---another one ---
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "
#End Region
    Protected Overrides Function ProcessDialogKey(ByVal keydata As System.Windows.Forms.Keys) As Boolean
        If Me.TextBox1.Focused Then
            Select Case keydata
                Case Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.Back  'accept digits only and Backspace
                    Return False
                Case Else
                    Return True
            End Select
        Else
            Return MyBase.ProcessDialogKey(keydata)
        End If
    End Function
End Class
'----another----------
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = NumbersOnly(e.KeyChar, TextBox1)
End Sub
   
Private Function NumbersOnly(ByVal pstrChar As Char, ByVal oTextBox As TextBox) As Boolean
    'validate the entry for a textbox limiting it to only numeric values and the decimal point
    If (Convert.ToString(pstrChar) = "." And InStr(oTextBox.Text, ".")) Then Return True 'accept only one instance of the decimal point
    If Convert.ToString(pstrChar) <> "." And pstrChar <> vbBack Then
    Return IIf(IsNumeric(pstrChar), False, True) 'check if numeric is returned
    End If
    Return False 'for backspace
End Function
Avatar of YZlat
     <script language="JavaScript">
            <!--
            //****************************************************************************
            //purpose            : Masks a numeric value by placing a dollar sign ($) and
            //                                 comma/commas in appropriate places.
            //example            :  onBlur="this.value=formatCurrency(this.value);"
            //input parameters   : numeric value
            //returns            : currency field with dollar sign and commas in appropriate places
            //function calls made: none
            //****************************************************************************
            
            function formatCurrency(num) {
                  num = num.toString().replace(/\$|\,/g,'');
                  if(isNaN(num))
                        num = "0";
                  sign = (num == (num = Math.abs(num)));
                  num = Math.floor(num*100+0.50000000001);
                  cents = num%100;
                  num = Math.floor(num/100).toString();
                  if(cents<10)
                        cents = "0" + cents;
                  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
                        num = num.substring(0,num.length-(4*i+3))+','+
                        num.substring(num.length-(4*i+3));
                  return (((sign)?'':'-') + '$' + num + '.' + cents);
            }
            
//-->
</script>

In your Page_Load put the following code:

Text1.Attributes.Add("onblur", "this.value=formatCurrency(this.value);"
Avatar of jxharding

ASKER

i just got ATTEMPT1 working but i dont like the component so much
then  i read the first post from iboutchkine, and i saw all the warnings that was given, and i thought
damn.
then i went to to check how the world renowned accounting program we bought handles this situation with the validation  , and guess what:
it also has all the potential problems iboutchkine mentioned!
so i think if its good enough for them, its good enough for me.
im just gonna try them all out.
thanks!
ibouthckine, id like to use this sub:

 Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles
TextBox2.KeyPress
        If Char.IsDigit(e.KeyChar) Then
            MsgBox("Digit entered")
        End If
        'disable non-digits
        e.Handled = Not Char.IsDigit(e.KeyChar)
    End Sub

is there any way to modify : "        e.Handled = Not Char.IsDigit(e.KeyChar)"
so i can use "." or "," as well to have decimal?
the value i want to enter is monetary

ASKER CERTIFIED SOLUTION
Avatar of iboutchkine
iboutchkine

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial