Home > SharePoint, webpart > Programmatically add a web part to SharePoint

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
coll.Add(webpart);
Advertisements
Categories: SharePoint, webpart
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: