Pages

Friday, November 13, 2009

SharePoint: Create blank Web Part Page Programmatically

If you ever need to create web part page from SharePoint Programmatically then how will you do so? The first thing I did was to follow how SharePoint actually do this. When you Click Site Settings -> Create -> Web Part Page, the following screen will come up.

image

Figure 1: Create web part page

I had noticed that the page is using _layouts/spcf.aspx so I had opened the page and found that its finally using /_vti_bin/owssvr.dll?CS=65001 for creating web part page. Going to explore the dll I found its not .net dll :-((. So its difficult to find how actually it works.

 

Then suddenly I found the solution by myself. The solution is to create a blank web part page and keep in the library. Then when I need to create another blank web part page I can just copy it and create new one. The following code snippet will copy the existing source file to destination.

public static string CopyFile(string sourceFileName, string listName, string destinationFileName)

        {

            try

            {

                SPList list = SPContext.Current.Web.Lists[listName];

                SPListItem sourceItem = null;

                foreach (SPListItem item in list.Items)

                {

                    if (item.Name.Equals(sourceFileName, StringComparison.OrdinalIgnoreCase))

                    {

                        sourceItem = item;

                        break;

                    }

                }

                string destinationUrl = sourceItem.Url.Replace(sourceItem.Name, string.Empty);

                destinationUrl = string.Format("{0}/{1}/{2}", SPContext.Current.Web.Url, listName, destinationFileName);

 

                sourceItem.CopyTo(destinationUrl);

 

            }

            catch (Exception exp)

            {

                return string.Format("Error: {0}", exp.Message);

            }

            return "Copied successfully";

        }

So if you call the function as shown below then it'll copy the SourceTemplate.aspx (which is the blank web part page) in list "site web part pages" to destination.aspx in the same list.

CopyFile("SourceTemplate.aspx", "Site Web Part Pages", "destination.aspx");

So the creating of web part page is implemented by copying an existing one. Good trick huh! :))

4 comments:

  1. Hi Sohel, stumbled on your blog. It is very nice to see you blogging regularly on sharepoint. Keep it up. - Shiplu

    ReplyDelete
  2. Thanks for your comment. Trying to do something helpful for dev community.

    ReplyDelete
  3. Did you ever find a way to actually create a "Web Part Page" programatically versus just copy a an existing blank Web Part Page?

    ReplyDelete
  4. It's described in my another post: http://ranaictiu-technicalblog.blogspot.com/2010/02/sharepoint-2007-create-web-part-page.html

    ReplyDelete

Note: Only a member of this blog may post a comment.