简体   繁体   English

为什么我的EventHandler不触发? (Asp.Net C#)

[英]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? 我正在以编程方式制作一些LinkBut​​ton,它们在一段时间内工作良好,但是现在事件没有触发,我不知道为什么?

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. ShowModalPopup存在并且全部存在,但是当我在Debug中运行它时,其中的任何内容都不会触发...由于某种原因,它没有被调用。 Any ideas? 有任何想法吗?


found my answer here: http://bytes.com/groups/net-asp/329287-linkbutton-event-not-firing 在这里找到我的答案: 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. 这是因为.NET如果未在viewstate中设置,则会在回发时对元素事件处理程序进行修改。 All you need to do is re-attach the eventhandler in the onload event. 您需要做的就是在onload事件中重新附加事件处理程序。

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. 这篇MSDN文章很好地概述了ASP.NET页面的生命周期。

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. 例如,对于在运行时添加的控件,与在声明式创建的控件的相同事件相比,在页面生命周期中,Init和Load事件的发生可能要晚得多。

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. 因此,从实例化它们的时间起,动态添加的控件和模板中的控件就会依次引发事件,直到它们赶上将其添加到Controls集合的事件为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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