Search code examples
sharepoint-2007content-type

Get Child Content Types of a Content Type


How can I get the child content types of a content type?

From here I've learned that, all the child content types have the contentTypeId begins with the parent's ID. So, I tried to use the suggested way that is in the link.

Let me show you what I've tried first:

        using (var site = new SPSite(SPContext.Current.Site.ID))
        {
            using (var web = site.RootWeb)
            {
                SPContentTypeId ctId = new SPContentTypeId(MasterContentTypeId);
                SPContentType masterCt = web.ContentTypes[ctId];

                var queryString = string.Empty;
                queryString += "<Where>";
                queryString += "<BeginsWith>";
                queryString += "<FieldRef Name='ContentTypeId'/>";
                queryString += "<Value Type='Text'>";
                queryString += MasterContentTypeId;
                queryString += "</Value>";
                queryString += "</BeginsWith>";
                queryString += "</Where>";

                SPSiteDataQuery query = new SPSiteDataQuery { Query = queryString };
                DataTable dt = web.GetSiteData(query);
                DataView dv = new DataView(dt);

                foreach (DataRow row in dt.Rows)
                {
                    //Do Something Necessary
                }
            }
        }

But the DataTable returns with no rows.

Is this the right way to do this but there's something missing or wrong; or am I doing this all wrong?


Solution

  • I guess I've found a solution. Here is the reference: link

    IEnumerable<SPContentType> descendantContentTypes = from SPContentType childCt in web.AvailableContentTypes
                                                                        where childCt.Id.IsChildOf(parentContentTypeId)
                                                                        select childCt;