SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What I want to do is just same with what I do when I add a list view web parts into a web page. The difference is that I want to do it programmatically.

I know how to import web parts to WebPartsManager and the web parts I have to use is XsltListViewWebPart. But I have no idea about how to create or get it.

Hope someone help me.


share|improve this question
up vote 2 down vote accepted

I've used this little helper function before:

public static XsltListViewWebPart MakeNewXsltListViewWebPart(SPList list, string webPartTitle)
    SPView defaultView = list.DefaultView;
    XsltListViewWebPart xsltListViewWebPart = new XsltListViewWebPart();
    xsltListViewWebPart.ID = "wpListView";
    xsltListViewWebPart.Title = webPartTitle;
    xsltListViewWebPart.ListName = list.ID.ToString("B").ToUpper();
    xsltListViewWebPart.ViewGuid = defaultView.ID.ToString("B").ToUpper();
    PropertyInfo nodeProp = defaultView.GetType().GetProperty("Node", BindingFlags.NonPublic | BindingFlags.Instance);
    XmlNode node = nodeProp.GetValue(defaultView, null) as XmlNode;
    XmlNode toolbarNode = node.SelectSingleNode("Toolbar");
    if (toolbarNode != null)
        if (!toolbarNode.Attributes["Type"].Value.Equals("Freeform"))
            toolbarNode.Attributes["Type"].Value = "Freeform";

    return xsltListViewWebPart;

You will want to customize some of the webpart's properties for your needs (ChromeType, AllowEdit, etc.)

Then to add it to a page, you can use LimitedWebPartManager on a webpart page :

Guid storageKey = Guid.Empty;
using (var manager = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
    var webPart = WebPartHelper.CreateWebPart(web, webPartName, manager);

    if (webPart != null)
        manager.AddWebPart(webPart, webPartZoneName, webPartZoneIndex);
        storageKey = manager.GetStorageKey(webPart);
share|improve this answer
Fantastic! It works completely. Thank you, Louis. – Toste May 23 '12 at 10:38

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.