Solved

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

Posted on 2004-04-22
5
1,339 Views
Last Modified: 2012-05-04
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
0
Comment
Question by:jxharding
  • 2
  • 2
5 Comments
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10887872
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
0
 
LVL 35

Expert Comment

by:YZlat
ID: 10888601
     <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);"
0
 

Author Comment

by:jxharding
ID: 10889180
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!
0
 

Author Comment

by:jxharding
ID: 10889644
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

0
 
LVL 28

Accepted Solution

by:
iboutchkine earned 500 total points
ID: 10889920
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Char.IsDigit(e.KeyChar) Or e.KeyChar = "."c Or e.KeyChar = ","c Then ' you can add more char if you want
            MsgBox("Digit entered")
        Else
            e.Handled = True
        End If
 End Sub
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

937 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

4 Experts available now in Live!

Get 1:1 Help Now