Thursday, May 1, 2008

Adding a ListView web part to SharePoint and MOSS

At the moment I'm pretty interested in looking at ways we can manage an existing SharePoint or MOSS infrastructure.

For example say you had a MOSS installation with 200 client colaboration sites and somebody wants to add a new web part to all these sites? Short of making the web part available to all sites and then asking the clients to add the web part themselves what can we do?

Below is a code snippet that shows how to add a new list view web part.

 
public static void AddListViewWebPart(SPWeb web
, SPList list
, SPView listView
, string fullOrRelativeUrl
, PersonalizationScope scope
, string webPartZoneID
, int webPartZoneIndex)
{
ListViewWebPart listViewWebPart = new ListViewWebPart();

listViewWebPart.ListName = list.ID.ToString("B").ToUpper();
listViewWebPart.ViewGuid = listView.ID.ToString("B").ToUpper();

SPLimitedWebPartManager wpManager =
web.GetLimitedWebPartManager(fullOrRelativeUrl, scope);

wpManager.AddWebPart(listViewWebPart as
System.Web.UI.WebControls.WebParts.WebPart
, webPartZoneID
, webPartZoneIndex);
}


Example usage from a console app. It adds a list view webpart using the default view to the top of the left webpart zone on the default.aspx page.

This method could also be called from a feature receiver.

Try it out.

 
namespace DeploymentConsole
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://vm-spdev-7497:1000/"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["New Library"];

Deploy.AddListViewWebPart(web
, list
, list.Views[0]
, "Default.aspx"
, PersonalizationScope.Shared
, "Left"
, 0);
}
}
}
}
}


I will also give code to add a custom web part in a future post.

No comments: