Welcome to Neudesic Blogs Sign in | Join | Help

Programmatically adding a Web Part in ASP.NET 2.0

Programmatically adding a Web Part to a WebPartZone is pretty straightforward:

WebPartManager1.AddWebPart(simpleWebPart, zone1, 0);

What matters is when the AddWebPart method is called. On a POST the Web Parts control set gets saved to the personalization data. On a GET however, the added Web Part does not get saved. This means that the next time you visit the page the Web Part that you just added is no longer there.

This happens because on a GET, by default; the flag that ultimately causes the personalization components to save the personalization data never gets set. The protected SetPersonalizationDirty method of the WebPartManager class sets this flag. By simply extending the WebPartManager class, we can set this flag:

namespace TestSite
{
    public class MyWebPartManager : WebPartManager
    {
        public void SetDirty()
        {
            // Invoke the protected SetPersonalizationDirty method     
            SetPersonalizationDirty();
        }
    }
}

Next, we replace the WebPartManager with the extended WebPartManager class on the page:

<%@ Register TagPrefix="testsite" Namespace="TestSite" %>
....
<testsite:MyWebPartManager ID="MyWebPartManager1" runat="server" />

Finally, we invoke the SetDirty method after adding the Web Part programmatically:

private void UpdateUI()
{
      MyWebPartManager1.AddWebPart(simpleWebPart, zone1, 0);
      MyWebPartManager1.SetDirty();      
}

In summary, by simply extending the WebPartManager class we added support for the saving any changes to the Web Parts controls set at any time.

Published Friday, February 10, 2006 9:08 AM by David Barkol

Comments

Anonymous comments are disabled