views:

163

answers:

3

Hi all, I have a usercontrol used in a masterpage. I have added a page with the masterpage.

Now I need to call a method of the user control from the page. How to do this? Please help.

A: 

This should get you your control even if it was added programatically:

In a member of the page you added:

TextBox FoundTextBox = (TextBox)this.Master.FindControl("RunAtServerTextBoxServerID");
Ahmed Khalaf
+1  A: 

Assuming that your method is public and your user control's type is YourUserControlsType, try this :

YourUserControlsType ctrlAtMasterPage = 
      (YourUserControlsType)Page.Master.FindControl("YouControlsID");
ctrlAtMasterPage.YourPublicMethod();
Canavar
A: 

If you don't have a member reference to the control you should consider decoupling the page from the control. In an ideal world, the page should not necessarily know about a control it may or may not contain. Therefore, you might look into an implementation of the MVP pattern.

There's a simple implementation of MVP here, and you can see the decoupling in action here. If you reverse the communication from the decoupling example (i.e. page fires an event that the control picks up), then basically, you've decoupled your page from the control. This has a benefit in that if your page changes and the control is no longer in use, the event is not picked up by anything and your page continues to execute with no problems. I find this much more suitable than a potential null reference exception when FindControl doesn't find the control and then you try to execute a method on it.

While decoupling may take a few extra minutes, in many scenarios it turns out to be a worthwhile endeavor.

Travis Heseman