Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

How can I use a content type programmatically?

example: I have a content type called "Doc Template1" and I have added it as a content type in my document library. And when I click New Document > Doc Template1; Microsoft Word opens up.

Now, how will I do this programmatically?

I have now retrieve my content types using

foreach (SPContentType cType in contentTypeCollection)

{ lstBox.Items.Add(cType.Name); }

Thanks!

share|improve this question

3 Answers 3

You need only change field value as in follow code.

item[SPBuiltInFieldId.ContentType] = "Content Type ID";
item.Update();
share|improve this answer

One way to get the content types of a specific document library is to access these via SPList.ContentTypes which returns a collection of the associated content types to that specific list or library. You can use it like so:

using (var site = new SPSite("http://somesharepointsite.com"))
{
   var web = site.RootWeb;
   var list = web.Lists["Some Library"];
   var contentTypeCollection = list.ContentTypes;
   // place your code here...
}

Instantiating a new site collection (with the SPSite) contructor is quite time and memory consuming. So if your situation allows it you should rahter use the SPContext.Current.Site or SPContext.Current.Web properties.

share|improve this answer

it's not so difficult.

     SPList docLib; //found your document liberary;

     docLib.ContentTypes.Add(web.ContentTypes.OfType<SPContentType>().Where(c => c.Name.Equals("Doc Template1", StringComparison.OrdinalIgnoreCase)).FirstOrDefault());
     docLib.Update();
share|improve this answer
    
I am currently trying your code. but where can I get .OfType ? –  Goms Mar 15 '12 at 23:55
1  
.OfType is part of Linq extension methods. the namespace is: System.Linq –  Jalali Shakib Mar 17 '12 at 7:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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