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
RIASAsked:
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.
0
RIASAuthor Commented:
Will a maskedtextbox do the trick?
Cheers
0
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.
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

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)
0
it_saigeDeveloperCommented:
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
		Else
			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)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        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.SuspendLayout()
		'
		'MaskedTextBox1
		'
		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)
		'
		'Form1
		'
		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.Controls.Add(Me.MaskedTextBox1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	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-
0

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!
0
AndyAinscowFreelance programmer / ConsultantCommented:
Just don't forget the disadvantages of that approach.
0
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.