textbox to accept only number and only 16 digits


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           
        End If      
    End Sub

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

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
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.
RIASAuthor Commented:
Will a maskedtextbox do the trick?
AndyAinscowFreelance programmer / ConsultantCommented:
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.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

AndyAinscowFreelance programmer / ConsultantCommented:
>>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)
In all honesty, a masked textbox would fit the bill as it already has validators in place.

Form1.vb -
Public Class Form1
	Private Sub OnMaskInputRejected(sender As Object, e As MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected
		MessageBox.Show(String.Format("{0} was rejected; {1}", e.Position, e.RejectionHint))
	End Sub

	Private Sub OnTypeValidationCompleted(sender As Object, e As TypeValidationEventArgs) Handles MaskedTextBox1.TypeValidationCompleted
		If e.IsValidInput Then
			If e.ReturnValue.ToString().Length < 16 Then
				MessageBox.Show("The entered card number must contain 16 digits.")
				e.Cancel = True
			End If
			MessageBox.Show("The entered card number must contain 16 digits.")
			e.Cancel = True
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing AndAlso components IsNot Nothing Then
            End If
        End Try
    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()
		Me.MaskedTextBox1 = New System.Windows.Forms.MaskedTextBox()
		Me.MaskedTextBox1.Location = New System.Drawing.Point(13, 13)
		Me.MaskedTextBox1.Mask = "0000000000000000"
		Me.MaskedTextBox1.Name = "MaskedTextBox1"
		Me.MaskedTextBox1.Size = New System.Drawing.Size(259, 20)
		Me.MaskedTextBox1.TabIndex = 0
		Me.MaskedTextBox1.ValidatingType = GetType(Integer)
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 44)
		Me.Name = "Form1"
		Me.Text = "Form1"

	End Sub
	Friend WithEvents MaskedTextBox1 As System.Windows.Forms.MaskedTextBox

End Class

Open in new window

Produces the following output -Attempting to evacuate the control with less than 16 digits in the card number.-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RIASAuthor Commented:
Works like charm mate!!!Thanks for all the efforts!
AndyAinscowFreelance programmer / ConsultantCommented:
Just don't forget the disadvantages of that approach.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.