2009-10-19 85 views

回答

7

首先添加這些使用語句。

using Microsoft.SharePoint; 
using Microsoft.SharePoint.WebPartPages; 
在你的代碼

然後

// 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); 

如果你想使用自定義視圖,嘗試玩這個:

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

希望它能幫助, W0ut

+1

非常感謝! – 2009-10-20 10:22:02

+0

有關http://stackoverflow.com/questions/1595915/create-a-dropdown-box-containing-list-documents-with-links-to-them的任何想法嗎? – 2009-10-21 16:15:22

1

您需要執行兩個步驟才能將Web部件添加到頁面。首先你必須創建你想要在頁面上顯示的列表。因此,您可以使用網站列表集合的Add()方法(SPListCollection)。

要顯示Web部件頁面上的列表,您必須使用頁面的SPLimitedWebPartManagerListViewWebPart添加到Web部件頁面。

+1

感謝弗洛!請你有任何例子或樣品嗎? – 2009-10-19 13:16:50

1

要使其更多地作爲功能接收器的一部分重用,您可以將splist和spview作爲一部分傳入方法:

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); 
     } 
    } 
} 

然後功能激活時調用它:

AddEventsListViewWebPart(welcomePage, "Right", 1, "Events", PartChromeType.TitleOnly, "Events", "Calendar"); 
相關問題