1

我有一个自定义文本框控件来验证输入(去除不需要的字符)。除了我还想对控件的实现进行进一步处理之外,这很好用。

示例我在表单上有 3 个“specialTextbox”。sText1、sText2 和 sText3。sText1 & sText2 按预期工作。但是,当sText3的值发生变化时,我需要在论坛上进行更改,所以我在表单中有一个处理程序来处理ctext更改事件:

Private Sub sText3(sender As Object, e As EventArgs) Handles sText3.TextChanged
  'do some stuff here
End Sub

但是,此例程似乎覆盖了自定义文本框的 OnTextChanged 方法。我已经尝试包含对 MyBase.OnTextChanged 的​​调用,但这仍然没有级联,无论我做什么,我似乎都无法让文本框完成其验证职责。

一定很简单,但我很难过!

这是一个覆盖文本框的类

Public Class restrictedTextBox
  Inherits Windows.Forms.TextBox

  Protected validChars As List(Of Char)

  Public Sub New(ByVal _validChars As List(Of Char))
    MyBase.New()

    validChars = _validChars
  End Sub

  Public Sub setValidChars(ByVal chrz As List(Of Char))
    validChars = chrz
  End Sub

  Protected Overrides Sub OnTextChanged(e As System.EventArgs)
    MyBase.OnTextChanged(e)

    Dim newValue As String = ""
    For Each c As Char In Me.Text.ToCharArray
      Dim valid As Boolean = False
      For Each c2 As Char In validChars
        If c = c2 Then valid = True
      Next

      If valid Then newValue &= c.ToString
    Next

    Me.Text = newValue
  End Sub
End Class

这是一个具有自定义文本框的表单

Public Class frmNewForm
  Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
      MessageBox.Show("the text from the restricted text is: " & txtRestricted.Text)
  End Sub
End Class

这是一个带有自定义文本框的表单,它实现了 TextChanged 事件

Public Class frmNewForm2
  Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
    MessageBox.Show("the text from the restricted text is: " & txtRestricted.Text)
  End If

 Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs) Handles txtRestricted.TextChanged
    'now that I have implemented this method, the restrictedTextBox.OnTextChanged() doesn't fire - even if I call MyBase.OnTextChanged(e)

    'just to be completely clear. the line of code below DOES get executed. But the code in restrictedTextBox.vb does NOT 
    lblAwesomeLabel.Text=txtRestricted.Text
  End Sub
End Class
4

1 回答 1

0

它会触发,但可能不是您实现它的方式。

您的示例代码没有用于文本框的空构造函数,这意味着您在将文本框添加到表单时很可能没有使用设计器。

但是您的表单显示它是由设计师创建的:

Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs) _
  Handles txtRestricted.TextChanged
End Sub

您发布的代码无法做到这一点。如果您正在以编程方式创建“新”控件,那么您也需要以编程方式连接事件。

删除处理程序并留下存根:

Private Sub txtRestricted_TextChanged(sender As Object, e As EventArgs)
  'yada-yada-yada
End Sub

然后当您创建一个新文本框时,将其连接起来:

txtRestricted = new restrictedTextBox(myCharsList)
AddHandler txtRestricted.TextChanged, AddressOf txtRestricted_TextChanged
Me.Controls.Add(txtRestricted)
于 2012-12-09T15:14:24.553 回答