views:

986

answers:

2

Hello,

I tried searching on the net to programmatically insert a List as a webpart in a webpart page but was not lucky enough.

Any thoughts or ideas how i could Programmatically insert a List as a webpart in a webpart page

Many Thanks!

+1  A: 

You need to perform two steps to add a web part to a page. First you have to create the list you want to show on the page. Therefore you can use the Add() method of the web site's list collection (SPListCollection).

To show the list on the web part page you have to add a ListViewWebPart to the web part page using the SPLimitedWebPartManager of the page.

Flo
Thanks Flo! have u got any example or sample please?
Mo
+1  A: 

First add these using statements.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

Then in your code

// First get the list
SPSite site = new SPSite("http://myserver");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["MyCustomlist"];

// Create a webpart
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Top";   // Replace this ith the correct zone on your page.
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();

// Get the web part collection
SPWebPartCollection coll = 
    web.GetWebPartCollection("default.aspx",    // replace this with the correct page.
    Storage.Shared);

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

If you want to use a custom view, try playing with this:

SPView view = list.GetUncustomizedViewByBaseViewId(0);
wp.ListViewXml = view.HtmlSchemaXml;

Hope it helps, W0ut

W0ut
thanks works great!
Mo
any idea about http://stackoverflow.com/questions/1595915/create-a-dropdown-box-containing-list-documents-with-links-to-them please?
Mo