Home Python VB.Net - TextBox, allow the use of numbers only

VB.Net - TextBox, allow the use of numbers only

Two examples to restrict the use of numbers only in a textbox, taking into account the decimal seperator of the host PC.

Example 1

The most "simple" way to limit the entry of data is presented below.

Open a new Windows Forms project

On the form, paste: A textbox A label A button

And paste this code into...

Public Class Form1 Dim Sep As Char Dim Nombre As Double Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Nombre = CDbl(TextBox1.Text) Label1.Text = Nombre End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Détecter le séparateur décimale de l'application. Sep = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator TextBox1.Focus() End Sub Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If Not (Char.IsNumber(e.KeyChar) Or e.KeyChar.Equals(Sep) Or Char.IsControl(e.KeyChar)) Then e.Handled = True End Sub End Class

Example 2

The method used in Example 1 lacks in flexibilty. Indeed, making use of the decimal point depends on the configuration of the host PC.

The advantage of this second solution is that the user can type in a point or a comma and the code will handle the changes depending on the configuration of PC.

Add a second form with the same components.

Paste the code into...

Public Class Form2 Dim Sep As Char Dim Nombre As Double Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Applique() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Detect the decimal point of the application. Sep = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator End Sub Private Sub Data_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Data.KeyDown If e.KeyCode = 13 Then Applique() End If End Sub Private Sub Data_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Data.TextChanged If Data.Text = Sep Then 'If the decimal point is typed is directly. Data.Text = "0" & Sep Data.SelectionStart = Len(Data.Text) ElseIf Not IsNumeric(Trim(Data.Text)) Then Beep() If Len(Data.Text) < 1 Then Data.Text = "" Else Data.Text = Microsoft.VisualBasic.Left(Data.Text, Len(Data.Text) - 1) Data.SelectionStart = Len(Data.Text) End If End If End Sub Sub Applique() Dim DT As String 'Change it to be compatible with the configuration of the host PC. DT = Replace(Data.Text, ".", Sep) DT = Replace(DT, ",", Sep) Label1.Text = CDbl(DT) On Error Resume Next Data.SelectionStart = 0 Data.SelectionLength = Len(Data.Text) Data.Focus() End Sub End Class

Download

  • Python

LEAVE A REPLY

Please enter your comment!
Please enter your name!