views:

153

answers:

3

I am using a user control that I created (just a .cs file not an .ascx file), that does some magic and depending on a value generated by the control, I need it to do something on the parent page that is 'hosting' the control. It needs to call a method under certain circumstances (method is on the parent control).

the control is placed on the parent page like so:

<customtag:MyControl ID="something" runat="server" />

I'm dynamically creating buttons etc on the control itself but when a button is clicked, let's say for example that there's a text box on the control and if the value of the textbox is "bob" it needs to call a method on the page that's housing the control...how can I accomplish this?

A: 

You should be able to get the Page hosting the control through the Parent property. However, that's going to be returned to you as a Control. You have to cast it to the type of your page in order to access any methods on the page which you have defined.

casperOne
+3  A: 

You could do what casperOne suggested, but I wouldn't advise it. This is tightly coupling your user control to your parent page, which kind of defeats the purpose of a user control.

Personally, I'd add an event to the user control (say, ButtonClicked) that the parent page can handle. In the event handler in your parent, deal with the event however you see fit. This way you can plug the user control into a different page at a later date and not have to worry about logic in the user control that requires a specific kind of parent page.

Dan Tao
A: 

I think that casperOne is on the right track, but you need to go a step further. I'm giong to make the assumption that this user control will be used on more then on page. (I normally write VB.Net, sorry if my C# is malformed)

Make a base page class (you can store it in your App_Code directory or in a project):

public class PageToInheritFrom : System.Web.UI.Page {
    public void SpecialFunction() {
    }    
}

Now make sure that all of your pages inherit from this page in your code behind file:

public partial class _Default : PageToInheritFrom {

}

Now in your user control you know what the page type is and can call

((PageToInheritFrom)this.Page).SpecialFunction();
Patricker