[.NET 2.0] Adding Web Parts programmatically
I'm playing around with the portal frameworks and web parts in .NET 2.0 and it looks powerful. The thing that bugs me most right now is the built in personalization stuff that remember everything I do on my web page (like closing a web part by mistake and not being able to get it back :)
At the moment I'm looking at the best way to programmatically add web parts from say another assembly and allow the user to add it to a zone. The way I'm doing it now is by implementing the abstract WebPart class and adding it to the zone.
A very simple Web Part class looks like this:
using System;
using System.Security.Permissions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public class MyWebPart : WebPart
{
public MyWebPart()
{
//comment to allow close
this.AllowClose = false;
}
public MyWebPart(String Title) : base()
{
this.Title = Title;
}
protected override void CreateChildControls()
{
Controls.Clear();
Label DisplayContent = new Label();
DisplayContent.Text = "Hello web part";
this.Controls.Add(DisplayContent);
ChildControlsCreated = true;
}
}
And I'm adding it to the zone like this:
private void AddPart()
{
MyWebPart myPart = new MyWebPart("MyPart");
WebPartManager1.AddWebPart(myPart, LeftZone, 0);
}
Problems I have now is that the Web Part disappeares sometimes and I don't know how add this Web Part to a CatalogZone. Not much info on the Net about stuff like this. Pity I didn't attend the TechEd, I'm sure there was lots of Web Parts coding samples there. If anyone knows the best way to do it, please let me know.
EDIT 1: It seems that you're not supposed to be using a CatalogZone when you want to add Web Parts at run time. Just implement you own kind of catalog and use the AddWebPart() to add it to the zone you want to have it in. The Web Part will saved in the personalization data.
EDIT 2: I've implemented my own catalog now by deriving from CatalogPart. See my other blog post for a sample.
Anyone working on doing a portal framework on top of this? Something like IBuySpy Portal but based on Web Parts instead of User Controls?