How to filter textbox input to numeric only?

前端 未结 9 1458
耶瑟儿~
耶瑟儿~ 2020-12-21 13:37

How do I suppress all data except numeric?

This is not working on KeyDown():

If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
          


        
9条回答
  •  醉梦人生
    2020-12-21 14:25

    You can check Char.IsDigit(e.KeyChar), but the best thing to do in this case is to create a subclass of TextBox and override IsInputChar(). That way you have a reusable TextBox control that you can drop anywhere so you don't have to re-implement the logic.

    (My VB is a bit rusty...)

    Public Class NumericTextBox : Inherits TextBox
    
        Protected Overrides Function IsInputChar(Byval charCode As Char) As Boolean
            If (Char.IsControl(charCode) Or Char.IsDigit(charCode)) Then
                Return MyBase.IsInputChar(charCode)
            Else
                Return False
            End If
        End Function
    
    End Class
    

提交回复
热议问题