所以我有一个文本框,我只想允许数字,我有代码来做它,它工作正常。但是我想在几个文本框中使用它,如何在不必在每个文本框的KeyDown和KeyPress Subs中重新键入相同的代码?
我在KeyDown Subs中使用的代码是
If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If
并在KeyPress潜艇中使用
If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If
我在几个文本框中使用此代码,并想知道如何清理这一点。我可以吗?感谢您的帮助和时间!
答案 0 :(得分:1)
你可以简单地设置事件的处理程序来处理其他对象,他们将共享该代码
Private Sub txtDim0_Validated(sender As Object, e As EventArgs) Handles txtDim0.Validated, txtDim1.Validated, txtDim2.Validated, txtDim3.Validated, txtDim4.Validated, txtDim5.Validated, txtDim7.Validated, txtDim7.Validated
Dim iNewIndex As Integer
If ErrorProvider1.Tag <> "" Then
For icount = 0 To Len(ErrorProvider1.Tag) - 1
iNewIndex = Val(ErrorProvider1.Tag.ToString.Substring(icount, 1))
ErrorProvider1.SetError(txtDims(iNewIndex), String.Empty)
Next
ErrorProvider1.Tag = ""
Else
' get the index based on the name
Dim index As Integer = Val(sender.name.ToString.Substring(Len("txtDim")))
ErrorProvider1.SetError(txtDims(index), String.Empty)
End If
End Sub
答案 1 :(得分:0)
您可以创建自己的TextBox控件版本,该控件继承自基本TextBox并使用您的自定义代码扩展它。
例如:
fakefolder/forget-password?email=...
然后重新编译您的项目,您应该看到新的Public Class CleverTextBox
Inherits TextBox
Private BACKSPACE As Boolean = False
Private Sub CleverTextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If
End Sub
Private Sub CleverTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If
End Sub
End Class
控件已添加到“工具箱”面板中,您可以将其拖放到表单上。