I recently saw a forum posting asking a fairly straight-forward question: “I want to create a Sharepoint Site Column for Publishing ImageField through C# code. Please help in understanding how to do this. A code snippet will be really helpful.” Although there’s plenty of documentation out there about how to add a WSS field to a site, I thought it might be helpful to provide a code snippet for adding a Rich Image Field to a site.

To answer the forum question, here’s sample code in a Feature Receiver:

using Microsoft.SharePoint;<br>using Microsoft.SharePoint.Publishing.Fields;
namespace BB.ProvisionImageField
{
    class FeatureReceiver: SPFeatureReceiver 
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPSite site = properties.Feature.Parent as SPSite)
            {
                using (SPWeb web = site.RootWeb)
                {
                    ImageField newImageField = new ImageField(web.Fields, "Image", "My Image Field");
                    newImageField.Group = "Publishing Columns";
                    newImageField.StaticName = "MyImageField";
                    newImageField.Title = "My Image Field";
                    newImageField.RichText = true;
                    newImageField.RichTextMode = SPRichTextMode.FullHtml;
                    web.Fields.Add(newImageField);
                }
            }
        }
    }
}

I wanted to point out something a little confusing. When you use the ImageField constructor, you pass in the FieldCollection you want to add your ImageField to. However, if you leave out the FieldCollection.Fields.Add() method, and try to call the ImageField.Update() method, you’ll get an error: “Value cannot be null. Parameter name: g”. The reason is that the field doesn’t have an ID assigned to it yet, so it won’t update the field. You can’t even modify the SchemaXml of the Field object, manually adding a new ID property, without getting the same error. The reason? SharePoint tries to retrieve the Field object first by its ID, in order to access the SchemaXml property. Without an ID, it can’t even find the Field to get to the Schema to modify it.

About Admin

Owner of Savvy Technical Solutions

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.