Code Snippet – Add Images on SharePoint Web Part Pages Programmatically

There are multiple ways you can add images programmatically on the SharePoint web part pages from the code. This article will provide you couple of code snippets to add images using Image Web Part and Content Editor Web Part. One of the benefits of adding images using web parts are end-users can specify different images.

Image Web Part
If you want to add non-clickable image as a place holder on the web part pages, use “ImageWebPart” to add image programmatically using following code snippet.

SPFile page = spWeb.GetFile("Home/Home.aspx");
using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
    try
    {
        lwpm.AddWebPart(
            new Microsoft.SharePoint.WebPartPages.ImageWebPart()
            {
                Title = "News & Events",
                AllowEdit = false,
                AllowClose = false,
                AllowHide = false,
                AllowMinimize = false,
                AllowConnect = false,
                AllowZoneChange = false,
                HorizontalAlignment = HorizontalAlignment.Left,
                ImageLink = "Images/industryNews.gif",
                ChromeType = PartChromeType.None
            },
            "Zone4",
            3);
    }
    finally
    {
        if (lwpm.Web != null)
        {
            lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
        }
    }
}

Content Editor Web Part with Hyperlink HTML
If you want to add clickable image on the web part pages, unfortunately “ImageWebPart” wouldn’t work. As a workaround, you can add “ContentEditorWebPart” programmatically and add hyperlink HTML as shown in following code snippet.

SPFile page = spWeb.GetFile("Home/Home.aspx");
using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
    try
    {
        // create a new XmlElement and put the results there
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlElement = xmlDoc.CreateElement("ContentElement");
        xmlElement.InnerText = "<a href='../Docs/MyDocs.aspx'><img src='Images/myDocs.gif'/></a>";

        lwpm.AddWebPart(
            new Microsoft.SharePoint.WebPartPages.ContentEditorWebPart()
            {
                Title = "My Documents",
                AllowEdit = false,
                AllowClose = false,
                AllowHide = false,
                AllowMinimize = false,
                AllowConnect = false,
                AllowZoneChange = false,
                Content = xmlElement,
                ChromeType = PartChromeType.None
            },
            "Zone3",
            1);
    }
    finally
    {
        if (lwpm.Web != null)
        {
            lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
        }
    }
}
Advertisements
This entry was posted in SP2010 Code Snippets. Bookmark the permalink.