NoviceToDotNet
NoviceToDotNet

Reputation: 10805

How to call a page method in the dynamically addedded usercontrol?

I am adding a user control dynamically on a page, the user control has a save button that takes data from both user control and page to save in the DB, in the same save method i want to access a method wrriten in the page, so i that mehod had code to rebind the grid kept in the page.

So how can i call a page method in the dynamically added user control?

Upvotes: 0

Views: 718

Answers (1)

Chris Gessler
Chris Gessler

Reputation: 23113

I was going to suggest creating a base class for your pages, but found an even better way to accomplish this task:

http://www.codeproject.com/Articles/115008/Calling-Method-in-Parent-Page-from-User-Control

Control code:

public partial class CustomUserCtrl : System.Web.UI.UserControl
{
    private System.Delegate _delWithParam;
    public Delegate PageMethodWithParamRef
    {
        set { _delWithParam = value; }
    }

    private System.Delegate _delNoParam;
    public Delegate PageMethodWithNoParamRef
    {
        set { _delNoParam = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void BtnMethodWithParam_Click(object sender, System.EventArgs e)
    {
        //Parameter to a method is being made ready
        object[] obj = new object[1];
        obj[0] = "Parameter Value" as object;
        _delWithParam.DynamicInvoke(obj);
    }

    protected void BtnMethowWithoutParam_Click(object sender, System.EventArgs e)
    {
        //Invoke a method with no parameter
        _delNoParam.DynamicInvoke();
    }
}

Page code:

public partial class _Default : System.Web.UI.Page
{
    delegate void DelMethodWithParam(string strParam);
    delegate void DelMethodWithoutParam();
    protected void Page_Load(object sender, EventArgs e)
    {
        DelMethodWithParam delParam = new DelMethodWithParam(MethodWithParam);
        //Set method reference to a user control delegate
        this.UserCtrl.PageMethodWithParamRef = delParam;
        DelMethodWithoutParam delNoParam = new DelMethodWithoutParam(MethodWithNoParam);
        //Set method reference to a user control delegate
        this.UserCtrl.PageMethodWithNoParamRef = delNoParam;
    }

    private void MethodWithParam(string strParam)
    {
        Response.Write(“<br/>It has parameter: ” + strParam);
    }

    private void MethodWithNoParam()
    {
        Response.Write(“<br/>It has no parameter.”);
    }
}

Upvotes: 2

Related Questions