Adding dynamically WebParts – Problems to move during first execution

There’s a “problem” when we try to add dynamically webparts to a page.

In my last project, I had problems to add some dinamicly webparts to able users to move it around the page.

When a webpart is dinamicly added to a page, in the first execution, if you try to move it, probably you’ll have the WebPartZones empty. It happens because the aspnet_personalizationPerUser table doesn’t know that a new webPart has been added to the page. This process will happen after the first post to the page.

To solve this situation, we have to do some changes to the code, and I’ll help you with this simple task.

1. Extending the WebPartManager control (creating a new class)

using System.Web.UI.WebControls.WebParts;
public class MyWebPartManager : WebPartManager
{

 public void setDirty()
 {
   SetPersonalizationDirty();
 }
}

The setDirty() method calls the protected SetPersonalizationDirty() methods of WebPartManager class. This way the aspnet_PersonalizationPerUser will know that there’s a new WebPart on page.

After you create the new WebPartManager called MyWebPartManager, you have to replace the WebPartManager control in the page.

2. Replacing the WebPartManager control

a) Registering the control on page
<@ Register TagPrefix=”myWPM” Assembly=”yourassembly” Namespace=”yournamespace” %>

b) Replacing the control on page
<myWPM:MyWebPartManager id=”WebPartManager1″ runat=”server”></myWPM:MyWebPartManager>

3. Calling the setDirty() method

WebPart myWebPart = WebPartManager1.CreateWebPart(userControl);
WebPartManager1.AddWebPart(myWebPart, WebPartZone1, 0);
WebPartManager1.setDirty();

Is not necessary to execute the setDirty() for each webpart added to a page, you can execute it once.

Thats it !!

As soon as possible I’ll post some news about WebParts.

Bye 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *