0

ページにユーザーコントロールを動的に追加しています。ユーザーコントロールには、ユーザーコントロールとページの両方からデータを取得してDBに保存する保存ボタンがあります。同じ保存メソッドで、ページに記述されたメソッドにアクセスしたいので、その方法には、ページに保持されているグリッドを再バインドするコードがありました。

では、動的に追加されたユーザー コントロールでページ メソッドを呼び出すにはどうすればよいでしょうか。

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 に答える