ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call

风格不统一 提交于 2019-12-05 17:32:28

By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():

protected override void OnLoad(EventArge e)
 { base.OnLoad(e);
   EnsureChildControls();

   var linkButtons = from c in AfterPageRepeater.Controls
                                                .OfType<RepeaterItem>()
                     where c.HasControls()
                     select c into ris
                        from lb in ris.OfType<LinkButton>()
                        select lb;

   foreach(var linkButton in linkButtons)
    { linkButton.Click += PageNavigateButton_Click
    }                          
 }

Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit.

From there it is easy enough to process because the CommandName and CommandArgument values are passed into the event and are readily accessible.

You need to make sure that the link button is re-added to the control tree and/or that the event is rewired up to the control before the event fires.

Article @ 4guysfromrolla

I've never done a SharePoint WebPart, so I don't know if this will apply. But if it were a plain-old apsx page, I'd say that by the time it's rendering, it's too late. Try adding the event handlers in the control's Init or PreInit events.


Edit: Wait, I think Dilli-O might be right. See the Adding Button Controls to a Repeater section at the end of http://www.ondotnet.com/pub/a/dotnet/2003/03/03/repeater.html. It's in VB.NET, but you can easily do the same thing in C#.

As others have pointed out, you're adding the event handler too late in the page life cycle. For SharePoint WebParts you'd typically want to override the class' OnInit/CreateChildControls methods to handle the activity.

YOu need your webpart to implement the INamingContainer marker interface, it is used by the framework to allow postbacks to return to the correct control... Also the controls in your webpart all need to have an ID.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!