简体   繁体   中英

Why isn't my EventHandler firing? (Asp.Net C#)

I am programatically making some LinkButtons, and they worked fine for a while, but now the events aren't firing and I can't figure out why?

This is what makes the button:

protected void MakeUploadButton(attachment a, PlaceHolder ph)
{
    LinkButton lb = new LinkButton()
    {
        Text = "Upload New " + a.attachment_type.type_name,
        CssClass = "button right",
        ID = "lb" + a.attachment_type.file_tag,
        CommandArgument = a.attachment_type_id.ToString(),
        CommandName = a.attachment_type.type_name,
        CausesValidation = false
    };
    lb.Click += new EventHandler(showModalPopup);
    lb.DataBind();
    ph.Controls.Add(lb);
}

ShowModalPopup exists and all, but when I run it in Debug, nothing inside of it ever fires... for some reason, it is not getting called. Any ideas?


found my answer here: http://bytes.com/groups/net-asp/329287-linkbutton-event-not-firing

It's because .NET nukes an elements event handlers on postback if they aren't set in viewstate. All you need to do is re-attach the eventhandler in the onload event.

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load
   If Page.IsPostBack Then
      Dim lb as ListButton = TryCast(Page.FindControl("IDOfControl"), LinkButton)
      lb.Click += new EventHandler(showModalPopup);
   End If
End Sub

Make sure that you create your controls on every page cycle (postback too). This MSDN article gives a good overview to the ASP.NET page life cycle.

Catch-up Events for Added Controls

If controls are created dynamically at run time or are authored declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively.

Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM