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
:
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:
<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
:
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:
Public Sub SetNumericInputMode(ByVal txtBox As RadTextBox)
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.