Numbers-Only Text Box


/ Published in: VB.NET
Save to your folder(s)

NumberTextBox is a control used to restrict input to numbers, function keys and arithmetic symbols only. Otherwise, it works just like a normal TextBox.


Copy this code and paste it in your HTML
  1. Option Strict On
  2. Imports System.Windows.Forms
  3. Public Class NumberOnlyTextBox
  4. Inherits System.Windows.Forms.TextBox
  5. Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
  6. Select Case e.KeyCode
  7. Case Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, _
  8. Keys.D8, Keys.D9, Keys.NumPad0, Keys.NumPad1, Keys.NumPad2, Keys.NumPad3, _
  9. Keys.NumPad4, Keys.NumPad5, Keys.NumPad6, Keys.NumPad7, Keys.NumPad8, _
  10. Keys.NumPad9
  11. 'number pressed
  12. If e.Shift And e.KeyCode <> Keys.D8 Then
  13. 'multiplication symbol still allowed
  14. e.SuppressKeyPress = True
  15. e.Handled = True
  16. Else
  17. MyBase.OnKeyDown(e)
  18. End If
  19. Case Keys.Add, Keys.Subtract, Keys.Divide, Keys.Multiply, Keys.Decimal, _
  20. Keys.Oemplus, Keys.OemPeriod, Keys.OemMinus, Keys.OemQuestion
  21. 'arithmetic symbol
  22. If e.Shift And (e.KeyCode = Keys.OemMinus Or e.KeyCode = Keys.OemQuestion) Then
  23. e.SuppressKeyPress = True
  24. e.Handled = True
  25. Else
  26. MyBase.OnKeyDown(e)
  27. End If
  28. Case Keys.Back, Keys.Back, Keys.Enter, Keys.Escape, Keys.Delete, Keys.Insert, Keys.Home, _
  29. Keys.End, Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, Keys.F6, Keys.F7, _
  30. Keys.F8, Keys.F9, Keys.F10, Keys.F11, Keys.F12, Keys.Tab, Keys.Up, _
  31. Keys.Down, Keys.Left, Keys.Right, Keys.Shift, Keys.ShiftKey, Keys.Control, _
  32. Keys.ControlKey, Keys.Alt
  33. 'misc keys that we still want to view events for
  34. MyBase.OnKeyDown(e)
  35. Case Else
  36. 'bad key, supress keystroke
  37. e.SuppressKeyPress = True
  38. e.Handled = True
  39. End Select
  40. End Sub
  41. End Class

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.