[vb.net] VB.net Need Text Box to Only Accept Numbers

I know this post is old but I wanted to share something I have implemented to turn a TextBox into what I call an IntBox.

First you need to make an extension with:

<Runtime.CompilerServices.Extension()> _
Public Function HandledStringtoInteger(s As String) As Integer
    Try
        If s = String.Empty Then
            Return 0
        Else
            Return Integer.Parse(s)
        End If
    Catch
        Dim result As String = String.Empty
        Dim ReturnInt As Integer
        Dim Parsed As Integer
        For Each Character In s.ToCharArray
            If Character = "-" Then
                If s.Substring(0, 1).ToString <> "-" Then
                    result = Character + result
                End If
            End If
            If Character = "." Then
                Exit For
            End If
            If Integer.TryParse(Character, Parsed) Then
                result = result + Parsed.ToString
            End If
        Next
        If result <> String.Empty Then
            If Integer.TryParse(result, ReturnInt) Then
                Return Integer.Parse(ReturnInt)
            Else
                If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
                    Return Integer.MaxValue
                ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
                    Return Integer.MinValue
                Else
                    Return Integer.Parse(ReturnInt)
                End If
            End If
        Else
            Return 0
        End If
    End Try
End Function

Then make a TextChanged event sub:

Private Sub TextBox_to_IntBox(sender As Object, e As TextChangedEventArgs) Handles YourTextBox.TextChanged
    If DirectCast(sender, TextBox).IsKeyboardFocused Then
        DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text.HandledStringtoInteger
        DirectCast(sender, TextBox).CaretIndex = DirectCast(sender, TextBox).Text.Length
    End If
End Sub

Then whenever the user enters text it evaluates the string and only returns numeric values that are within the bounds of a standard Integer. With the "-" character you can change the integer from positive to negative and back again.

If anyone sees anything that can improve this code let me know but my tests show this works fantastic to make an IntBox.

EDIT: I found another method that can work if you use properties in your code. (Note this will need a separate property per TextBox)

First create the property:

Public Class Properties
    Implement INotifyPropertyChanged

    Private _Variable as Integer
    Public Property YourProperty as Object
    get
      Return _Variable
    end get
    set(value as Object)
      _Variable = value.ToString.ToInteger 'I will give the ToInteger extension code later
    end set
    end property
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

Public Sub OnPropertyChange(ByVal e As PropertyChangedEventArgs)
    If Not PropertyChangedEvent Is Nothing Then
        RaiseEvent PropertyChanged(Me, e)
    End If
End Sub
End Class

Then make the binding in your window's main class:

Public WithEvents _YourVariable as New Properties

Public Sub New()
    InitializeComponent()
With YourTextBox
  .SetBinding(Textbox.TextProperty, New Binding("YourProperty"))
  .DataContext = _YourVariable
End With
End Sub

Finally here is the ToInteger Extension Code I set up:

''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
    Dim S As String = X.ToString
    Try
        If S = String.Empty Then
            Return I
        Else
            Return Integer.Parse(S)
        End If
    Catch
        Dim result As String = String.Empty
        Dim ReturnInt As Integer
        Dim Parsed As Byte
        For Each Character In S.ToCharArray
            If Character = "-" Then
                If S.Substring(0, 1).ToString <> "-" Then
                    result = Character + result
                End If
            End If
            If Character = "." Then
                Exit For
            End If
            If Byte.TryParse(Character, Parsed) Then
                result = result + Parsed.ToString
            End If
        Next
        If result <> String.Empty Then
            If Integer.TryParse(result, ReturnInt) Then
                Return Integer.Parse(ReturnInt)
            Else
                If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
                    Return Integer.MaxValue
                ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
                    Return Integer.MinValue
                Else
                    Return Integer.Parse(ReturnInt)
                End If
            End If
        Else
            Return I
        End If
    End Try
End Function

With all these combined whenever they type something into the box it will act as if it were a textbox but when they change focus the ToInteger extension will set the value as an integer into the property and return it to the textbox.

Meaning that if the operator entered "-1w3" after focus changes it will return as "-13" automatically.

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python