Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Allowing Only Numeric Input in a TextBox

0.00/5 (No votes)
7 May 2023CPOL 5.9K  
How to allow only numeric input in TextBox
In this post, you will learn to allow only numeric input in a TextBox.

You may have seen a Windows textbox that would disallow non-numeric input, showing an error message like in the following screenshot:

This can be easily accomplished from .NET by applying the ES_NUMBER style to the textbox:

VB.NET
Public Sub SetNumericInputMode(ByVal txtBox As TextBox)
    Dim style As Int32 = GetWindowLong(txtBox.Handle, GWL_STYLE)
    SetWindowLong(txtBox.Handle, GWL_STYLE, style Or ES_NUMBER)
End Sub

Of course, SetWindowLong has to be declared properly:

VB.NET
<DllImport("user32.dll")>
Private Shared Function SetWindowLong( _
     ByVal hWnd As IntPtr, _
     ByVal nIndex As Integer, _
     ByVal dwNewLong As IntPtr) As Integer
End Function

Now what if you’re using the RadTextBox control from the Telerik RadControls for WinForms? The following code works for a normal textbox, compiles, but will not work for a RadTextBox:

VB.NET
SetNumericInputMode(textBox1.Handle);

The reason is that the RadTextBox is just a container for the native Win32 textbox. Any style changes have to be applied directly to the actual textbox, not the container. The following will work:

VB.NET
Public Sub SetNumericInputMode(ByVal txtBox As RadTextBox)
  'special handling for RadTextbox as the actual Win32 textbox is hidden underneath
  Dim hwnd As IntPtr = CType(txtBox.TextBoxElement.Children(0), _
                             RadTextBoxItem).HostedControl.Handle
  Dim style As Int32 = GetWindowLong(hwnd, GWL_STYLE)
  SetWindowLong(hwnd, GWL_STYLE, style Or ES_NUMBER)
End Sub

Notice that ES_NUMBER only prevents user from entering non-numeric (0..9) input for the textbox. It does not stop user from pasting random text. For more advanced features, I suggest something like MaskedTextBox.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)