Search code examples
asp.netsharepoint-2010web-partspageloadwebpartpage

Why is OnPreRender being called over and over again?


In my Sharepoint 2010 WebPart, I have this code:

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    if (this.dpsvisWebPart != null && this.dpsvisWebPart.CustomTitleProp != null)
    {
        lbl_Title.Text = String.Format("<h1>{0}</h1>", this.dpsvisWebPart.CustomTitleProp.ToString());

        if (this.dpsvisWebPart.CheckboxGenSection1)
        {
            GenerateSection1();
        }
        if (this.dpsvisWebPart.CheckboxGenSection2)
        {
            GenerateSection2();
        }
        if (this.dpsvisWebPart.CheckboxGenSection3)
        {
            GenerateSection3();
        }
        if (this.dpsvisWebPart.CheckboxGenSection4)
        {
            GenerateSection4();
        }
        if (this.dpsvisWebPart.CheckboxGenSection5)
        {
            GenerateSection5();
        }
        if (this.dpsvisWebPart.CheckboxGenSection6)
        {
            GenerateSection6();
        }
        if (this.dpsvisWebPart.CheckboxGenSection7)
        {
            GenerateSection7();
        }

        if (AnyCheckboxSelected())
        {
            // Create Save button
            this.Controls.Add(new LiteralControl("<br />"));
            Button btnSave = new Button();
            btnSave.Text = "Save";
            btnSave.Click += new EventHandler(btnSave_Click);
            this.Controls.Add(btnSave);

            AddVerticalSpace();
        }
    }
}

On testing my WebPart (clicking the button, thus - presumably - executing the btnSave_Click handler, I found that nothing was being saved.

Stepping through the code, I see that OnPreRender is being reached - in fact, over and over again.

So, I added this to the WebPart class:

private bool PreRenderAlreadyRun = false;

...and then changed the beginning of OnPreRender() to this:

protected override void OnPreRender(EventArgs e)
{
    if (PreRenderAlreadyRun) return;
    PreRenderAlreadyRun = true;
    base.OnPreRender(e);
    . . .

...but PreRenderAlreadyRun is always false when OnPreRender is entered, which happens over and over. Other breakpoints are not reached (the button click, etc.) presumably because the page is in an endless loop.

How can I get OnPreRender() to run only once? Or should this code be in Page_Load() instead of OnPreRender(), or...???


Solution

  • The solution was to move the code that was in OnPreRender() to Page_Load()

    Apparently, just like at the stockyard, rendering happens many times, while the page is only loaded once. That's my theory, and I'm stickin' to it (for now, anyway).