1

I have a custom control "BedGrid" that contains a collection of custom controls, each of which has a click handler on them. In the Page_Load event of my Parent page, I generate a collection of BedGrids, and wire them up to an event handler. 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.

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). So, I want to cache the collection of BedGrids like so:

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..

What am I missing? All of this is happening in Page_Load, so why is the event not firing? Everything else is fine, meaning that the controls and their children draw properly..

4

1 回答 1

0

这不起作用的原因是因为必须在回发时重新创建控件,并且连接事件,以便它们触发。

请看,由于服务器是无状态的,要在对象上触发事件,需要重新创建该对象并将其读取到表单中。

如何缓存数据库结果并继续循环以构建新的、添加和连接控件?

于 2013-06-11T13:46:29.700 回答