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.



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);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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