Link to home
Start Free TrialLog in
Avatar of RIAS
RIASFlag for United Kingdom of Great Britain and Northern Ireland

asked on

textbox to accept only number and only 16 digits

Hello,

Any suggestions on how to make a textbox numeric with 16 digits of card number .

have this code on:

Private Sub TxtCard_Number_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtCard_Number.KeyPress
        Dim tb As TextBox = CType(sender, TextBox)
        If Not IsNumeric(e.KeyChar) Then    'Check if Numeric           
            ShowPassFail(False)
        Else
            ShowPassFail(True)
        End If      
      
    End Sub


 Private Sub ShowPassFail(ByVal pass As Boolean)
        If pass Then
            Me.TxtCardHlder.Focus()
        Else
            MessageBox.Show("Please enter numbers only", "Card Number Information!")
        End If
        Me.TxtCard_Number.Clear()
        Me.TxtCard_Number.Focus()
    End Sub

Open in new window


Cheers
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

I would make a new class - based on a TextBox - and have this as the object on the form.
The class would provide a handler for the KeyPress event (like you have or another event such as TextChanged - copy/paste) but it would not display a messagebox should a non valid character (eg. digit) be entered instead just beeping (and/or flashing) and ignoring the input.
It would also provide a boolean result when queried if the contents are of a valid format.
Avatar of RIAS

ASKER

Will a maskedtextbox do the trick?
Cheers
ps.  Why separate class?  Simple, the control can be used elsewhere or even multiple times on the same form without you having to re-invent the wheel.
>>Will a maskedtextbox do the trick?

Most of what you wanted, the length specification might be a bit tricky.  That would still require something on the form itself rather than in the code with the control.  (You could use the MaskedTextBox as the base for this custom control I suggested rather than just a TextBox)
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

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
Avatar of RIAS

ASKER

Works like charm mate!!!Thanks for all the efforts!
Just don't forget the disadvantages of that approach.