Q: How do I pass data back to the page from
a user control?
A: You could take
an approach similar to the previous solution; that is, by calling a method on a
strongly-typed reference to the page from within the user control:
CType(Page, UserControlHostPage).MyCustomSub()
However, this creates a circular reference, which is generally considered to be
a questionable design decision because of object-oriented principles such as encapsulation.
Such tightly coupled relationships are discouraged. One reason is that it would
tie the control to this particular page, thereby limiting reuse. There are ways
around that with Interfaces and such, but that’s where things start to get rather
sloppy. It is considered preferable for child objects to raise events instead of
directly referencing the parent. To raise an event, the event must first be declared
within the user control’s class:
Public Event
ButtonClicked()
Then the event can be raised to the page with a single line of code:
RaiseEvent ButtonClicked()
The page can then handle the control’s event with a simple declaration and event
handler:
Protected WithEvents
MyUserControl1 As MyUserControl
Private Sub
MyUserControl1_ButtonClicked() _
Handles MyUserControl1.ButtonClicked
Response.Write("User control's button was clicked.")
End Sub