c# - 将 UserControl 中的事件添加到嵌套 UserControl 中的按钮

标签 c# asp.net events user-controls

我有一个 UserControl,它包含另一个带有 Button 的 UserControl。 我想在第一个 UserControl(父级)中向该按钮添加一个事件。 我尝试这样做:

void Page_Init()
{
    var btn = ChildControl.FindControl("SearchButton") as Button;
    btn.Click += new EventHandler(this.SearchButton_Click);
}

btn 为空。我该怎么做?

最佳答案

FindControl不会递归搜索目标对象控件的子控件,因此首先获取嵌套控件,然后通过它的 ID 搜索按钮的子控件:

var btn = ChildControl.FindControl("NestedControl")
    .FindControl("SearchButton") as Button;

btn.Click += new EventHandler(this.SearchButton_Click);

关于c# - 将 UserControl 中的事件添加到嵌套 UserControl 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386929/

相关文章:

c# - DDD富域模型和聚合根

c# - 在 C# 中将 Xml 反序列化为对象

c# - 类中的静态函数返回该类的实例

python - 单击按钮后抓取数据

c# - LINQ to Entities 无法识别 MVC 4 中的方法 'System.String ToString()' 方法

javascript - 从可点击的 Google map 叠加层传播鼠标事件

c# - 如何在数据库中存储本地目录路径?

c# - Paypal 定期付款计费频率

javascript - 在我的网站上使用事件跟踪

c++ - 跨线程使用事件句柄 - C++