Prash's Blog

Programmatically Add SPList as Webpart on SPWeb using ListViewWebPart November 13, 2009

Filed under: SharePoint — prazjain @ 2:11 pm
Tags: ,

Here I would show how to add a list (that you already have in your site), on your default.aspx page for your web.

Step through of the code:

1) Get the file reference to the page where you want to display the webpart.

2) Check if the file exists, if not then we do not make any changes.

3) Get the reference to your list

4) Create a ListViewWebPart

5) Set ZoneID for ListViewWebPart to where you want to display the webpart i.e Left, Top etc.

6) Set ListName to the list you want to display in the webpart.

7) Set the ViewGuid to the guid of the View you are adding in the webpart

8) Get SPLimitedWebPartManager for the web.

9) Add the webpart to the SPLimitedWebPartManager

Code Sample

/// <summary>

/// Sets up the web part to display in default view

/// </summary>

/// <param name="web"></param>

private static void SetUpWebparts(SPWeb web)


SPFile file = web.GetFile("default.aspx");

if (file.Exists)


SPList projectHistoryList = web.Lists[StringConstants.ProjectHistory];

ListViewWebPart wp = new ListViewWebPart();

wp.ZoneID = "Top";

wp.ListName = projectHistoryList.ID.ToString("B").ToUpper();

wp.ViewGuid = projectHistoryList.DefaultView.ID.ToString("B").ToUpper();

SPLimitedWebPartManager coll = web.GetLimitedWebPartManager(web.Url + "default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

coll.AddWebPart(wp, "Top", 1);




Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s