SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an application that loads all of my content types into a drop down list. When an item in the drop down list is selected I would like to get a list of the columns for that content type but each one only returns Title and ContentType. Here is the code I am using:

    protected void ddl_ContentTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        SPContentType ct = new SPContentType(SPBuiltInContentTypeId.Document,SPContext.Current.Web.ContentTypes,ddl_ContentTypes.SelectedValue);
        foreach (SPField f in ct.Fields)
        {
           //do stuff with each field.  Only returns Title and ContentType
        }
    }

Is there something I should be doing differently. Is it bad that I am using the built in Document content type for the ParentContentType?

share|improve this question
up vote 3 down vote accepted

According to MSDN, this construction will create new blank content type with ddl_ContentTypes.SelectedValue as it's name:

SPContentType ct = new SPContentType(
    SPBuiltInContentTypeId.Document,
    SPContext.Current.Web.ContentTypes,
    ddl_ContentTypes.SelectedValue);

What you do need, is to retrieve one of the existing content types, based on it's name. Please, try this code instead of the fragment above:

SPContentType ct = SPContext.Current.Web.ContentTypes[ddl_ContentTypes.SelectedValue];
share|improve this answer
    
Doh! That fixed it, thanks! – Abe Miessler Apr 11 '11 at 19:02

To explain the difference, your original code is creating a NEW content type in the target collection SPContext.Current.Web.ContentTypes:

SPContentType ct = new SPContentType(SPBuiltInContentTypeId.Document,SPContext.Current.Web.ContentTypes,ddl_ContentTypes.SelectedValue);

While the code in the answer (SPContentType ct = SPContext.Current.Web.ContentTypes[ddl_ContentTypes.SelectedValue];) is retrieving the existing content type from the target SPWeb collection.

share|improve this answer

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.