简体   繁体   English

自定义控件事件在缓存控件集合时不会触发?

[英]Custom control events don't fire when control collection is cached?

I have a custom control "BedGrid" that contains a collection of custom controls, each of which has a click handler on them. 我有一个自定义控件“ BedGrid”,其中包含一组自定义控件,每个自定义控件都具有一个单击处理程序。 In the Page_Load event of my Parent page, I generate a collection of BedGrids, and wire them up to an event handler. 在父页面的Page_Load事件中,我生成了BedGrids的集合,并将它们连接到事件处理程序。 This all works fine, when I generate the BedGrids on each Page_Load... The grandchild is clicked, fires the event up to the BedGrid, which alerts my Parent Page and everything goes as planned. 当我在每个Page_Load上生成BedGrid时,所有这些工作正常。单击孙子,将事件触发到BedGrid,该事件会通知我的父页面,一切按计划进行。

The problem is, it's slow.. Generating all those custom controls on each Page_Load doesn't make sense (especially with trips to the backend). 问题是,它很慢。。在每个Page_Load上生成所有这些自定义控件是没有意义的(尤其是到后端的旅行)。 So, I want to cache the collection of BedGrids like so: 因此,我想像这样缓存BedGrids的集合:

protected void Page_Load(object sender, EventArgs e)
{
    DrawBedGrids();
}

protected void DrawBedGrids()
{   
    if (CachedBedgrids == null)
    {
        CachedBedgrids = new List<BedGrid>();

        //Hit DB here and generate list of buildings....

        foreach (Building b in buildings)
        {
            BedGrid bg = new BedGrid(b);
            bg.RaiseAlertParentPage += new EventHandler(BedGrid_Clicked);
            CachedBedgrids.Add(bg);
        }
    }
    else
    {
        foreach (BedGrid bg in CachedBedgrids)
        {
            somePanel.Controls.Add(bg);
        }
    }
}

protected List<BedGrid> CachedBedgrids
{
    get
    {
        try { return (List<BedGrid>)Session["CachedBedgrids"]; }
        catch { return null; }
    }
    set { Session["CachedBedgrids"] = value; }
}

And it all breaks.. The events never fire... Even if I add 一切都破了..这些事件永远不会触发...即使我添加

bg.RaiseAlertParentPage += new EventHandler(BedGrid_Clicked);

to the "else" right before I add the BedGrid to the panel.. 在将BedGrid添加到面板之前,将其移至“ else”。

What am I missing? 我想念什么? All of this is happening in Page_Load, so why is the event not firing? 所有这些都是在Page_Load中发生的,那么为什么不触发该事件? Everything else is fine, meaning that the controls and their children draw properly.. 其他一切都很好,这意味着控件及其子项可以正确绘制。

The reason this doesn't work is because the controls must be recreated on the post back, and events wired up, for them to fire. 之所以不起作用,是因为必须在回发时重新创建控件,并关联事件以使其触发。

See, since the server is stateless, to fire an event on an object, that object needs recreated AND readded to the form. 看到,由于服务器是无状态的,因此要在对象上触发事件,则需要重新创建该对象并将其读入表单。

How about cache the database result instead and continue the loop otherwise to build new, add, and hookup the controls? 取而代之,如何缓存数据库结果,然后继续循环,以建立新的,添加和连接控件的方式呢?

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

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