Programmatically add a web part to SharePoint

To add an web part to a page (e.g. default.aspx) in SharePoint use the following code

// Get a reference to a web and a list  
SPSite site = new SPSite("http://localhost:8000");  
SPWeb web = site.OpenWeb();  
SPList list = web.Lists["Tasks"];  
// Instantiate the web part  
ListViewWebPart webpart = new ListViewWebPart();  
webpart.ZoneID = "Left";  
webpart.ListName = list.ID.ToString("B").ToUpper();  
webpart.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();  
// Get the web part collection  
SPWebPartCollection coll =  web.GetWebPartCollection("default.aspx", Storage.Shared);  
// Add the web part  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.