Tuesday, April 1, 2008

Dynamic Webparts: missed events and twice load issue

While developing a portal which has dynamic webparts created, it was observed that control events were not firing. Also page_load function was called more than once. These issues got resolved on setting the personalization state dirty after adding or deleting a webpart. The personalization state can be set Dirty by calling WebPartManager SetPersonalizationDirty function. Since this method is protected, it can not be called directly. To call this function, a custom WebPartManager is required. The following explains it.

1) Create a custom WebPartManager which exposes only a single function SetDirty.



using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
public class NewWebPartManager : WebPartManager
{
public NewWebPartManager() { }

public void SetDirty()
{
this.SetPersonalizationDirty();
}
}

}


2) Use the custom webpart in the page as given below:


<%@ Register Namespace="Samples.AspNet.CS.Controls" TagPrefix="sample" %>
...
<sample:NewWebPartManager ID="WebPartManager1" runat="server" >
</sample:NewWebPartManager>

No comments: