Calling a method on the parent page from a custom control

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

the control is placed on the parent page like this:

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

      

I am dynamically creating buttons etc. in the control itself, but when the button is clicked, say for example that there is a textbox in the control and if the value of the textbox is "bob", it needs to call a method on the page the control is in ... how can I do this to do?

+2


a source to share


3 answers


You could do what casperOne suggested, but I would not recommend it. This hardcodes your user control to your parent page which type defeats the purpose of the user control.



Personally, I add an event to a custom control (say ButtonClicked

) that the parent page can handle. In your parent's event handler, you deal with the event as you see fit. This way, you can connect the custom control to another page at a later time and not worry about the logic in the custom control that requires a specific parent page.

+3


a source


You can get the page the control is on via the parent property . However, this will be returned to you as a control. You have to point it to your page type in order to access any methods on the page you define.



0


a source


I think casperOne is on the right track, but you need to move on. I giong to assume that this custom control will be used more than a page. (I usually write VB.Net, sorry if my C # is wrong)

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

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

      

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

public partial class _Default : PageToInheritFrom {

}

      

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

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

      

0


a source







All Articles