Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons.

In the RenderContent call in the Webpart I've got some code to add event handlers:

        ArrayList nextPages = new ArrayList();
        //populate nextPages ....
        AfterPageRepeater.DataSource = nextPages;
        AfterPageRepeater.DataBind();

        foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
        {
            if (oRepeaterControl is RepeaterItem)
            {
                if (oRepeaterControl.HasControls())
                {
                    foreach (Control oControl in oRepeaterControl.Controls)
                    {
                        if (oControl is LinkButton)
                        {
                            ((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
                        }
                    }
                }
            }
        }

The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.

Any ideas? I'm stumped how to do this.

like image 712
Gordon Thompson Avatar asked Dec 17 '22 10:12

Gordon Thompson


2 Answers

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
    }                          
 }
like image 85
Mark Cidade Avatar answered Dec 24 '22 00:12

Mark Cidade


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.

like image 42
Dillie-O Avatar answered Dec 24 '22 01:12

Dillie-O