views:

45

answers:

2

I was going through an article on event bubbling in asp.net and came to know that although it is possible to subscribe to the click event of a user control's button from the containing page, "doing so would break some of the object oriented rules of encapsulation". A better idea is to publish an event in the user control to allow any interested parties to handle the event.

My question is that exactly how does a direct subscription to the button's click event from a containing page would break the object oriented rules of encapsulation?

Apologies if its a dumb question. :|

Thanks!

+3  A: 

The idea is that the button of the control is an implementation detail of the UI of the control. If you republish the click event you could reimplement that button as an ImageButton, LinkButton, etc.

I think it's OK to attach an event handler at the page level to the button if the button is a permanent fixture of the UI. It saves a lot of event code, especially with a lot of buttons.

BC
Yeah, understood. Thanks for the help!
Dienekes
+3  A: 

The Button is supposed to be encapsulated by the UserControl.

If the Page binds directly to events on the button, then the page is now dependent on the inner workings of the UserControl.

The Page should be consuming the UserControl, not the UserControl's button. If the author of the UserControl later wants to remove the button and use some fancy new method of firing its "Submit" event, your page could be broken because the button may no longer exist.

For that matter, if the owner of the UserControl decides in v1.1 to rename the button from btnSubmit to SubmissionButton, it could break your page, as well.

Better to consume the UserControl and let it be concerned with its own inner workings.

Toby
Hmm got it.. that means the button is an internal implementation of the UC, it should ideally not be directly accessed by an external page. Doing so, would make the page dependent on the existing implementation within the UC.. :)Thanks a lot for helping me understand!
Dienekes
One more thing, what's the best way to access text of a label control present in the user control from the containing page?
Dienekes
If it were me, I'd add a string property to the UserControl that would initially be a pass-through to the label. I'd name it something meaningful withint the user control: QuestionText, DescriptionText, etc. For instance: `public string DescriptionText { get { return this.DescriptionLabel.Text; } set { DescriptionLabel.Text = value; } }`
Toby
Cool.. thanks for increasing my understanding in implementing OOPS.. :)
Dienekes