开发者

Mulitple linkbuttons in user control needs to call event handler in the aspx page

开发者 https://www.devze.com 2023-02-06 10:41 出处:网络
I have multiple us开发者_StackOverflower controls on a page and each of them have multiple linkbuttons that perform the same logic on the server side. Is there a way for all the linkbuttons to have th

I have multiple us开发者_StackOverflower controls on a page and each of them have multiple linkbuttons that perform the same logic on the server side. Is there a way for all the linkbuttons to have the same event handler that is defined in the code behind of the page?

If needed, I can change the linkbuttons to be any other HTML or ASP.NET control as long as it can support a clickable image.


Inside your usercontrol create an event and wire it up. Then call it from the linkbuttons OnClick event handler:

UserControl.ascx:

<asp:LinkButton
runat="server"
id="linkbutton1"
OnClick="LinkButtonClicked">
Click Me
</asp:LinkButton>
<asp:LinkButton
runat="server"
id="linkbutton2"
OnClick="LinkButtonClicked">
Click Me Again
</asp:LinkButton>

UserControl.ascx.cs

public event EventHandler UserControlLinkClick;

protected void LinkButtonClicked(object sender, EventArgs e)
{
   if (this.UserControlLinkClick!= null)
       {
           this.UserControlLinkClick(this, e);
       }
}

Inside your parent page wire up the user controls UserControlLinkClick:

protected override void OnInit(EventArgs e)
{
    MyUserControl uc = LoadControl("~/PathToUserControl.ascx");
    uc.UserControlLinkClick += new EventHandler(MyUserControl_UserControlLinkClick);
}

protected void MyUserControl_UserControlLinkClick(object sender, EventArgs e)
{
    //this code will execute when the usercontrol's LinkButtonClicked event is fired.
}

Hope that helps!!


Create an Event/Delegate in your custom control. Then in your page code behind, you can add event handlers or subscribe methods to the delegate.

Link for Events

Link for Delegates

Hope this helps

0

精彩评论

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

关注公众号