开发者

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

开发者 https://www.devze.com 2023-01-02 03:24 出处:网络
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 开发者_JAVA百科render a number of these controls on the page - imagine a lis

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 开发者_JAVA百科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','')


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!


I had a similar problem once that might be the same thing.

In short, since you are dynamically creating the buttons, after the postback they don't exist. Thus, when ASP.NET Webforms looks for the event, it can't find anything.

When does your repeater get databound? Try rendering the buttons to the page again in the postback (even as a test) to see if that does the trick.


Are the UserControl's IDs same on every postback?

0

精彩评论

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