Content Types Programmatically

on Friday, August 14, 2009



SPContentType CustomContentType = new SPContentType(p_web.AvailableContentTypes["Document"], p_web.ContentTypes, "InvoiceContentType");
// A string Field
p_web.Fields.Add("InvoiceNumber", SPFieldType.Number, true);
SPFieldLink fLink1 = new SPFieldLink(p_web.Fields["InvoiceNumber"]);
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);

SPList list = p_web.Lists["Employee Data"];
p_web.Fields.AddLookup("Vendor Name", list.ID, false);
SPFieldLookup lookupfield = (SPFieldLookup)p_web.Fields["Vendor Name"];

// Set the remote lookup list
//lookupfield.LookupList = list.ID.ToString();
// Set the remote field
lookupfield.LookupField = "FullName";
lookupfield.Update();
SPFieldLink fLink4 = new SPFieldLink(lookupfield);
CustomContentType.FieldLinks.Add(fLink4);
p_web.ContentTypes.Add(CustomContentType);
CustomContentType.Update();

Attach ContentType to List
SPContentType invoiceContentType = p_web.ContentTypes["InvoiceContentType"];
Guid invoiceListId = p_web.Lists.Add("Invoice", "Invoice LIst", SPListTemplateType.DocumentLibrary);
SPList list = p_web.Lists[invoiceListId];
invoiceContentType = list.ContentTypes.Add(invoiceContentType);
list.Update();
for (int i = list.ContentTypes.Count - 1; i >= 0; i--)
{
if(list.ContentTypes[i].Id != invoiceContentType.Id)
list.ContentTypes.Delete(list.ContentTypes[i].Id);
}
list.Update();

0 comments: