如何在动态添加的usercontrol中调用页面方法?

时间:2012-06-26 14:17:16

标签: asp.net

我在页面上动态添加用户控件,用户控件有一个保存按钮,用于从用户控件和页面获取数据以保存在DB中,在同一个保存方法中我想访问方法wrriten页面,所以我有mehod有代码来重新绑定页面中保留的网格。

那么如何在动态添加的用户控件中调用页面方法呢?

1 个答案:

答案 0 :(得分:2)

我打算建议为你的页面创建一个基类,但找到了更好的方法来完成这个任务:

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

控制代码:

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();
    }
}

网页代码:

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.”);
    }
}