Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

Regards,

share|improve this question
add comment

1 Answer 1

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";
         }
    }

    defaultView.Update();
    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);
        webPart.Dispose();
    }
}
share|improve this answer
    
Fantastic! It works completely. Thank you, Louis. –  Toste May 23 '12 at 10:38
add comment

Your Answer

 
discard

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.