从主叫用户控制父页面的方法 [英] Calling a method in parent page from user control

查看:155
本文介绍了从主叫用户控制父页面的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个aspx页面注册的用户控制
在用户控制按钮的单击事件,我怎么叫这是有父页面的codebehind的方法?

I've a user control registered in an aspx page On click event of a button in the user control, how do i call a method which is there in the parent page's codebehind?

感谢。

推荐答案

下面是使用事件弗雷迪·里奥斯(从Web应用程序项目C#)所建议的典型例子。这假定您要使用一个现有的委托,而不是让你自己和你没有被事件参数传递什么具体的父页面。

Here is the classic example using events as suggested by Freddy Rios (C# from a web application project). This assumes that you want to use an existing delegate rather than make your own and you aren't passing anything specific to the parent page by event args.

在用户控件的code-后面(如果不使用适应必要的code-后面或C#):

In the user control's code-behind (adapt as necessary if not using code-behind or C#):

public partial class MyUserControl : System.Web.UI.UserControl
{
    public event EventHandler UserControlButtonClicked;

    private void OnUserControlButtonClick()
    {
        if (UserControlButtonClicked != null)
        {
            UserControlButtonClicked(this, EventArgs.Empty);
        }
    }

    protected void TheButton_Click(object sender, EventArgs e)
    {
        // .... do stuff then fire off the event
        OnUserControlButtonClick();
    }

    // .... other code for the user control beyond this point
}

在您订阅事件像这样的页面本身:

In the page itself you subscribe to the event with something like this:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // hook up event handler for exposed user control event
        MyUserControl.UserControlButtonClicked += new  
                    EventHandler(MyUserControl_UserControlButtonClicked);
    }
    private void MyUserControl_UserControlButtonClicked(object sender, EventArgs e)
    {
        // ... do something when event is fired
    }

}

这篇关于从主叫用户控制父页面的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆