0

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

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

4

1 回答 1

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.”);
    }
}
于 2012-06-26T14:24:10.807 回答