Create a webpart page with an webpart with in it programmatically

前端 未结 2 776
-上瘾入骨i
-上瘾入骨i 2021-01-22 01:34

I want to create several webpart pages (programmatically) with custom web parts in it. I have searched the internetz but couldn\'t find anything that I could get to work.

<
2条回答
  •  面向向阳花
    2021-01-22 02:16

    OK, did a little digging... here is my solution.

    using(SPSite site = new SPSite("http://my.dev.com"))
    {
        using(SPWeb web = site.OpenWeb())
        {
            SPFile page = web.GetFile("SitePages/Welcome.aspx");
            using(SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                string errMsg = string.Empty;
                SPFile myWebPart = web.GetFile("_catalogs/wp/myWebPart.webpart");
                XmlTextReader read = newXmlReader(myWebPart.OpenBinaryStream());
                var wp = manager.ImportWebPart(read, out errMsg);
                manager.AddWebPart(wp, "", 1);
                manager.SaveChanges(wp);
            }  
        }
    }
    

提交回复
热议问题