When you expand one of Visual Basic's built in controls, avoid building
in a cascading Change event. This occurs when internal UserControl code
changes a constituent control's value. Doing so triggers the constituent
control's Change() event. Most likely, you'll have also exposed this
event to the developer. If the developer has placed code in the
UserControl's Change() event, then this will be triggered as well. For
instance, suppose you create an ActiveX Control project and add a
standard textbox as a constituent control. Next, you add the basic code:
Private mstrText As String
Public Event Change()
Private Sub Text1_Change()
MsgBox "Text1 Change"
RaiseEvent Change
End Sub
Public Property Get Text() As String
Text = mstrText
End Property
Public Property Let Text(Val As String)
mstrText = Val
End Property
Private Sub UserControl_ExitFocus()
Text1.Text = "Hello, " & Text1.Text
End Sub
Under this scenario, the UserControl will modify the textbox's text
whenever it loses the focus. However, suppose a developer places the
UserControl on a standard form and adds the following code:
Dim X as Integer
Private Sub UserControl11_Change()
X = X + 1
MsgBox X
End Sub
Now, every time the UserControl loses focus, Visual Basic increments X by
one-probably not what the developer had in mind.
To avoid the unintentional consequences cascading Change events can cause,
consider adding an internal public Boolean variable to the UserControl that
tracks internal changes vs. external ones, like this:
Private blnInternal as Boolean
Private Sub Text1_Change()
If Not blnInternal Then
MsgBox "Text1 Change"
RaiseEvent Change
End If
End Sub
Private Sub UserControl_ExitFocus()
blnInternal = True
Text1.Text = "Hello, " & Text1.Text
blnInternal = False
End Sub