I am adding an XsltListViewWebPart from code behind, my code is:

        static void Main(string[] args)
        SPSite site = new SPSite("http://bipc11:1234/sites/publishing1");
        SPWeb web = site.RootWeb;
        web.AllowUnsafeUpdates = true;
        SPLimitedWebPartManager webParts = web.GetLimitedWebPartManager(web.Url + "/SiteAssets/webparts.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
        SPList list = web.Lists["Images"];
        XsltListViewWebPart webPart = new XsltListViewWebPart();
        webPart.ListId = list.ID;
        webPart.XslLink = web.Url + "/Style Library/Custom View/ViewCart.xsl";
        webParts.AddWebPart(webPart, "Right", 0);
        Console.WriteLine("Web Part Added Successfully");

Images is the library in which pictures are stored and the path web.Url +"/Style Library/Custom View/ViewCart.xsl specifies the copy of file AssetPicker.xsl which renders data in thumbnail view.

My problem is that webpart displays this output instead of displaying this.

What am I missing?

1 Answer 1


If you think right view is not included in the XsltListViewWebPart, then you can get the instance of the correct view and add it to the webpart:

SPView view = list.Views["Thumbnails"];
webPart.ViewId= view.ID.ToString("B").ToUpper()
  • Thanks sir, but I want to make some changes in the view i.e. I want to put small icon before each image title. So, if I modify the view it will be applied to all libraries, that's why I copied the AssetPicker file.
    – users1100
    Sep 18, 2013 at 5:06
  • Am I following right way? @Nadeem Yousuf
    – users1100
    Sep 18, 2013 at 5:06
  • The view is associated to a single list/library. Modifying it wont have any impact on other libraries/lists in the site. Sep 18, 2013 at 5:17
  • Ok, I tried your code but it throws error that webPart.ViewId is int and view.ID is of type Guid
    – users1100
    Sep 18, 2013 at 5:31
  • Then I tried other way like : webPart.ViewGuid=list.Views["Thumbnails"].ID.ToString(); but it shows error that "Exception has been thrown by the target of an invocation" at the line of adding the web part from web part manager.
    – users1100
    Sep 18, 2013 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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