You are hereBlogs / Niral's blog / Create a SharePoint Content Type programmatically
Create a SharePoint Content Type programmatically
Sometimes it is necessary to create a Sharepoint Content Type by code, specially when batch creating content types. The following code snippet shows how a sharepoint content type can be created in C#. I have also included some not-so-simple field types like choice and lookup.
using (SPSite p_site = new SPSite(urlToSite))
{
using (SPWeb p_web = p_site.OpenWeb())
{
SPContentType CustomContentType = new
SPContentType(p_web.AvailableContentTypes["ParentContentType"],
p_web.ContentTypes, "MyContentType");
// A string Field
p_web.Fields.Add("NumberColumn", SPFieldType.Number);
SPFieldLink fLink1 = new SPFieldLink(p_web.Fields["NumberColumn"]);
CustomContentType.FieldLinks.Add(fLink1);
// A required number field
p_web.Fields.Add("StringColumn", SPFieldType.Text, true);
SPFieldLink fLink2 = new SPFieldLink(p_web.Fields["StringColumn"]);
CustomContentType.FieldLinks.Add(fLink2);
//A Choice Field
p_web.Fields.Add("ChoiceColumn", SPFieldType.Choice, false);
SPFieldChoice choicefield = (SPFieldChoice)p_web.Fields["ChoiceColumn"];
// Add a group to the filed
choicefield.Group = "MyGroup";
// Add choices
choicefield.Choices.Add(string.Empty);
choicefield.Choices.Add("Yes");
choicefield.Choices.Add("No");
// Set the default choice
choicefield.DefaultValue = string.Empty;
choicefield.Update();
SPFieldLink fLink3 = new SPFieldLink(choicefield);
CustomContentType.FieldLinks.Add(fLink3);
p_web.Fields.Add("LookupColumn", SPFieldType.Lookup, false);
SPFieldLookup lookupfield = (SPFieldLookup)p_web.Fields["LookupColumn"];
// Set the remote lookup list
lookupfield.LookupList = new Guid("guidofremotelist");
// Set the remote field
lookupfield.LookupField = "remotefieldname";
lookupfield.Update();
SPFieldLink fLink4 = new SPFieldLink(lookupfield);
CustomContentType.FieldLinks.Add(fLink4);
p_web.ContentTypes.Add(CustomContentType);
CustomContentType.Update();
}
}
- Niral's blog
- Add new comment
- 7310 reads
site.Fields.AddLookup("LookupColumn", new Guid("guidofremotelist"), false); SPFieldLookup newField = (SPFieldLookup)site.Fields["LookupColumn"]; ...Hope someone finds that useful.