Search code examples
sharepointmosswss

Add web part programmatically


I'm using the following code to add web parts to a page programmatically, however i've a problem that after the page is postedback the web part is not visible on the page, I need to refresh the page to get the web part visible.

SPSite site = new SPSite("http://syngdcds0032:23547");
site.AllowUnsafeUpdates = true;   
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;  
SPList list = web.Lists["Assets"];
SPView setView = list.Views["VVV"];

// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
//wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
wp.ViewGuid = setView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll =
    web.GetWebPartCollection("http://syngdcds0032:23547/Pages/AssetSearch1.aspx",
    Storage.Shared);

// Add the web part
coll.Add(wp);

Solution

  • Some suggestions

    • use SPContext.Current.Site, SPContext.Current.Web instead of creating new instances of those objects - it's "expensive" in sense of memory usage
    • try to use LimitedWebpartManager class (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.splimitedwebpartmanager_methods.aspx) for adding the webpart to the page. In this case, you don't have to add the webpart to the page in every call, you have to do it once in the page's lifetime. The code will look something like this

          Dim op As WebPartPages.SPLimitedWebPartManager
          op = oWeb.GetLimitedWebPartManager("default.aspx", Web.UI.WebControls.WebParts.PersonalizationScope.Shared)
          oWP = New WebPartPages.ListViewWebPart
          oWP.ListName = oWeb.Lists("Workflow tasks").ID.ToString("B").ToUpper()
          oWP.AllowClose = False
          oWP.AllowHide = False
          oWP.AllowMinimize = False
          oWP.AllowZoneChange = True
          oWP.ExportMode = Web.UI.WebControls.WebParts.WebPartExportMode.All
          oWP.Title = "Darba uzdevumi"
          oWP.ChromeType = Web.UI.WebControls.WebParts.PartChromeType.TitleOnly
          oWP.ViewGuid = oWeb.Lists("Workflow tasks").Views("All Items").ID.ToString("B").ToUpper()
          oWP.ZoneID = "Right"
          op.AddWebPart(oWP, "Right", 1)