Number Only in a TextBox

There are many fields in an information that we must only type a number in a textfield or in a textbox such as phone number, zip code, or any fields that must have a number type only. So, now we will begin this filtering a textbox into number only. Now, let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application. 2. Next, add only one textBox named TextBox1 so that we can filter to input letters in the textbox. You must design your layout like this: design 3. Now put this code in your code module.
  1. Public Class Form1
  2.  
  3.     Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
  4.         If (e.KeyChar < "0" OrElse e.KeyChar > "9") _
  5.                     AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> "," Then
  6.             e.Handled = True
  7.         End If
  8.     End Sub
  9. End Class

Explanation:

We use keypress event in our Textbox because this event occurs when the user presses and releases an ANSI key. We use the variable e As System.Windows.Forms.KeyPressEventArgs and has a method name of KeyChar or a key character that will hold only a value from 0 to 9. The period (.) and comma(,) are included in the textbox because it is a part of the number system as we code
  1. AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> "," Then
  2.             e.Handled = True

Output:

output Download the source code below and try it! :) Best Regards,

Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer
Mobile: 09079373999
Telephone: 826-9296
E-mail:[email protected]

Visit and like my page on Facebook at: Bermz ISware Solutions

Subscribe at my YouTube Channel at: SerBermz

Add new comment