开发者

Add event in UserControl to button which is in nested UserControl

I have a UserControl开发者_开发技巧, which contains another UserControl with Button. I want to add an event to that button in first UserControl (parent). I tried to do:

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

but btn is null. How can I do that ?


FindControl doesn't recursively search through the children of the controls of the target object, so get the nested control first, then search it's child controls for the button by it's ID:

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

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


Rather than subscribing to child control events , why not create an event inside your user control such as :

public event EventHandler<EventArgs> SearchClicked;

protected virtual void OnSearchClicked()
{
     if (this.SearchClicked != null)
     {
         this.SearchClicked.Invoke(this,EventArgs.Empty);
     }
}

then invoke this in your search click

private void btnSearch_Click(object sender,EventArgs e)
{
    this.OnSearchClicked();
}

then you can subscribe to this event anywhere you use the user control


You should be able to do controlInstance.controls.FindControl("Searchbutton") for a control that is one-level below the final control that is under the page object.


Because FindControl is not recursive (as @GenericTypeTea mentions), you can either create an extension method for UserControl that IS recursive to accomplish this or provide a public property in your UserControl that returns the button as a reference. Then you should be able to use:

ChildControl.MyButtonProperty.Click += new EventHandler(this.SearchButton_Click);

The recursive extension method might be more useful in the long run if this is a common problem though.

Edit
Also, because you're doing this in Page_Init, the button may not be initialized within the child control since the child control's init gets called after the page's init. It may be necessary to perform this action in the InitComplete event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜