如何将文本框输入过滤为仅数字? [英] How to filter textbox input to numeric only?

查看:30
本文介绍了如何将文本框输入过滤为仅数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何抑制除数字以外的所有数据?

How do I suppress all data except numeric?

这不适用于 KeyDown():

If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
    e.Handled = True
End If

推荐答案

你可以勾选 Char.IsDigit(e.KeyChar),但是这种情况下最好的做法是创建一个 TextBox 的子类并覆盖 IsInputChar().这样你就有了一个可重用的 TextBox 控件,你可以把它放在任何地方,这样你就不必重新实现逻辑.

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.

(我的VB有点生疏...)

(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

这篇关于如何将文本框输入过滤为仅数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆