Click here to Skip to main content
15,885,985 members
Articles / Desktop Programming / Windows Forms

Allowing Only Numeric Input in a TextBox

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 May 2023CPOL 5.4K   1  
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)


Written By
Technical Writer
Singapore Singapore
Since 2008, ToughDev has been publishing technical sharing articles on a wide range of topics from software development to electronics design. Our interests include, but are not limited to, Android/iOS programming, VoIP products, embedded design using Arduino/PIC microcontrollers, reverse-engineering, retro-computing, and many others. We also perform product reviews, both on new and vintage products, and share our findings with the community. In addition, our team also develops customized software/hardware solutions highly adapted to suit your needs. Contact us for more information.

Comments and Discussions

 
-- There are no messages in this forum --