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);
Some suggestions
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