自定义控件mybase.OnTextChanged没有触发

时间:2012-11-22 14:17:41

标签: vb.net winforms controls

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

示例我在表单上有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

1 个答案:

答案 0 :(得分: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)