Search code examples
asp.netuser-controlsrepeaterloadcontrolitemdatabound

ASP.NET Button click not caught (button in user control which is dynamically loaded in Repeater)


I have written a user control that captures some user input and has a Save button to save it to the DB. I use a repeater to render a number of these controls on the page - imagine a list of multiple choice questions with a Save button by each question.

I am loading the user control inside the repeater's ItemDataBound event like this (code simplified):

Protected Sub rptAssignments_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptAssignments.ItemDataBound

    Dim CurrentAssignment As Assignment = DirectCast(e.Item.DataItem, Assignment)
    Dim ctl As UA = CType(LoadControl("~\Controls\UA.ascx"), UA)

    ctl.AssignmentID = CurrentAssignment.AssignmentID
    ctl.Assignment = CurrentAssignment.AssignmentName
    ctl.EnableViewState = True

    e.Item.Controls.Add(ctl)
End Sub

FYI, I need to load the control at runtime rather than specify it in the ItemTemplate because a different control could be used for each row.

In the user control, there is a linkbutton like this:

<asp:LinkButton ID="lbnUpdate" runat="server" Text="Update" OnClick="lbnUpdate_Click" />

... and a button click handler like this:

Protected Sub lbnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbnUpdate.Click
   ' my code to update the DB
End Sub

The problem is that when the Save button is clicked, the page posts back, but lbnUpdate_Click is not called. The Page_Load event of the page itself is called however.

I should mention that the repeater is part of a user control, and that user control is loaded inside another user control (this is a DotNetNuke site which makes heavy use of user controls). The Save button link looks like this:

javascript:__doPostBack('dnn$ctr498$AssignmentsList$rptAssignments$ctl04$ctl00$lbnUpdate','')

Solution

  • This problem exemplifies how webforms outsmarts itself.

    You have to reconstitute the Repeater, either by re-binding or from viewstate, to have sub-controls raise events. The price you pay is either another trip to your data source or all that redundant data stored on the client in the viewstate. Shameful!