Calling a method in parent page from user control(从用户控件调用父页面中的方法)
问题描述
我在 aspx
页面中注册了一个用户控件在用户控件中的按钮单击事件时,如何调用父页面代码隐藏中的方法?
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?
谢谢.
推荐答案
这是 Freddy Rios 建议的使用事件的经典示例(来自 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.
在用户控件的代码隐藏中(如果不使用代码隐藏或 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
}
}
这篇关于从用户控件调用父页面中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从用户控件调用父页面中的方法


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01