2009-10-19 6 views

Répondre

7

Ajoutez d'abord ces instructions using.

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

Puis dans votre 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); 

Si vous souhaitez utiliser une vue personnalisée, essayez de jouer avec ceci:

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

Hope it helps, W0ut

+1

merci fonctionne très bien! –

+0

une idée sur http://stackoverflow.com/questions/1595915/create-a-dropdown-box-containing-list-documents-with-links-to-them please? –

1

Vous devez effectuer deux étapes pour ajouter un composant WebPart à une page. Vous devez d'abord créer la liste que vous souhaitez afficher sur la page. Vous pouvez donc utiliser la méthode Add() de la collection de listes du site Web (SPListCollection).

Pour afficher la liste sur la page Web, vous devez ajouter un ListViewWebPart à la page Web en utilisant le SPLimitedWebPartManager de la page.

+1

Merci Flo! avez-vous un exemple ou un échantillon s'il vous plaît? –

1

Pour rendre cela plus réutilisable dans le cadre d'un récepteur de fonction, vous pourriez passer dans le splist et spview dans le cadre d'un Méthode:

static public void AddEventsListViewWebPart(PublishingPage page, string webPartZoneId, int zoneIndex, string webPartTitle, PartChromeType webPartChromeType, string listName, string viewname) 
{ 
    using (SPLimitedWebPartManager wpManager = page.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared)) 
    { 
     SPWeb web = page.PublishingWeb.Web; 
     SPList myList = web.Lists.TryGetList(listName); 
     using (XsltListViewWebPart lvwp = new XsltListViewWebPart()) 
     { 
      lvwp.ListName = myList.ID.ToString("B").ToUpperInvariant(); 
      lvwp.Title = webPartTitle; 
      // Specify the view 
      SPView view = myList.Views[viewname]; 
      lvwp.ViewGuid = view.ID.ToString("B").ToUpperInvariant(); 
      lvwp.TitleUrl = view.Url; 
      lvwp.Toolbar = "None"; 
      lvwp.ChromeType = webPartChromeType; 
      wpManager.AddWebPart(lvwp, webPartZoneId, zoneIndex); 
     } 
    } 
} 

Et puis l'appeler lors de l'activation de fonction:

AddEventsListViewWebPart(welcomePage, "Right", 1, "Events", PartChromeType.TitleOnly, "Events", "Calendar"); 
Questions connexes