如何通过代码添加listviewwebpart

时间:2014-06-10 13:03:23

标签: c# sharepoint sharepoint-2010

在我目前的生产代码中,我们有以下完美的工作:

XsltListViewWebPart clientInfoWebPart = new XsltListViewWebPart();
                                    clientInfoWebPart.Title = "Client Info";
                                    clientInfoWebPart.WebId = web.ID;
                                    clientInfoWebPart.ListName = clientInfoListSP.ID.ToString("B").ToUpper();
                                    clientInfoWebPart.ChromeType = PartChromeType.TitleOnly;
                                    clientInfoWebPart.Toolbar = "None";
                                    clientInfoWebPart.XmlDefinition = clientInfoHomePageview.GetViewXml();
                                    clientInfoWebPart.ViewGuid = clientInfoHomePageview.ID.ToString("B").ToUpper();
                                    clientInfoWebPart.Hidden = true;
                                    mgrPageManager.AddWebPart(clientInfoWebPart, "Header", 0);
                                    mgrPageManager.SaveChanges(clientInfoWebPart);

然而,在安装SP1之后,我们在SaveCHanges行中遇到了这个问题。

(Object reference not set to an instance of an object.) System.NullReferenceException   
 at Microsoft.SharePoint.WebPartPages.BaseXsltListWebPart.EnsureView()    
 at Microsoft.SharePoint.WebPartPages.XsltListViewWebPart.get_View()    
 at Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChangesCore(SPLayoutProperties layoutProperties, Boolean httpGet, Boolean saveCompressed, Boolean skipRightsCheck, Boolean skipSafeAgainstScriptCheck, WebPartTypeInfo& newTypeId, Byte[]& newAllUsersProperties, Byte[]& newPerUserProperties, String[]& newLinks)    
 at Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChangesInternal(SPLayoutProperties layoutProperties, Boolean skipRightsCheck, Boolean skipSafeAgainstScriptCheck)    
 at Microsoft.SharePoint.WebPartPages.SPWebPartManager.SaveChanges(Guid storageKey)    
 at Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.SaveChanges(WebPart webPart)    

问题是,这里发生了什么?我该如何解决?我需要保存更改吗?为什么它没有抛出异常PRE-SP1而现在它失败了??

2 个答案:

答案 0 :(得分:1)

尝试将代码中的ListId设置为列表的GUID,然后您不需要打扰使用ListName。 ViewGuid也不应该是GUID而不是字符串吗?

还尝试设置页面的ListId查询字符串,例如

SomePage.aspx?ListId=GUID

将GUID替换为列表的GUID。

如何设置ListItemId?

答案 1 :(得分:0)

我遇到了同样的问题,我注意到您发布了same question here并找到了解决方案。

  

这没有解决问题,但是删除保存更改修复了它,显然,在添加webpart时,不需要保存更改(在SP1之后),代码正在工作PRE-SP1