2

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?

3

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];
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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