SharePoint How-To: Create WebPart Page programmatically

SharePoint How-To: Create WebPart Page programmatically

As it turned out, the task of creating webpart pages programmatically isn't obvious as it may seem at first blush.

To solve it we should use ProcessBatchData:

/// <summary>
/// Create new webpart page
/// </summary>
/// <param name="list">List to keep page</param>
/// <param name="pageTitle">Page title</param>
/// <param name="layoutTemplate">Layout template id</param>
/// <returns>Operation result</returns>
private static string CreateWebPartPage(SPList list, string pageTitle, int layoutTemplate)
    const string newItemTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                    "<Method ID=\"0,NewWebPage\">" +
                                    "<SetList Scope=\"Request\">{0}</SetList>" +
                                    "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
                                    "<SetVar Name=\"ID\">New</SetVar>" +
                                    "<SetVar Name=\"Type\">WebPartPage</SetVar>" +
                                    "<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
                                    "<SetVar Name=\"Overwrite\">true</SetVar>" +
                                    "<SetVar Name=\"Title\">{1}</SetVar>" +
    var newItemXml = string.Format(newItemTemplate, list.ID, pageTitle, layoutTemplate);
    return list.ParentWeb.ProcessBatchData(newItemXml);
var web = SPContext.Current.Web;
var pagesLibrary = web.GetList("Pages");
CreateWebPartPage(pagesLibrary, "MyPage", 2);
Values for LayoutTemplate parameter:
Full Page, Vertical
Header, Footer, 3 Columns
Header, Left Column, Body
Header, Right Column, Body
Header, Footer, 2 Columns, 4 Rows
Header, Footer, 4 Columns, Top Row
Left Column, Header, Footer, Top Row, 3 Columns
Right Column, Header, Footer, Top Row, 3 Columns

or here.

Leave a Comment
  • Please add 6 and 8 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
  • Nice one..Just a thought, could be a Gallary post instead of wiki?

  • Why? Gallery is using for tools or scripts! Wiki is using for articles!

  • Hi,

    What if i need to create a webpart page with custom template.

  • Nice.

Page 1 of 1 (4 items)