Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
40 views
in SharePoint Server by 39 47 54

I'm working on a SharePoint 2019 event receiver and I need to count the number of items in a list that belong to a specific content type. I've tried using the SPList.ItemCount property, but it gives the total item count, not the count for a specific content type.

Here's what I've tried so far:

public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);

    SPItem item = properties.ListItem;   

    SPList list = item.ParentList;


    SPContentType itemContentType = list.ContentTypes.GetById(item.ContentTypeId);

    // How to count items of the same content type as the current item?
}

I'm looking for a way to efficiently count the items of the same content type as the newly added item in SharePoint event Receiver.

Any suggestions or code examples would be greatly appreciated.


1 Answer

1 like 0 dislike
by 159 198 381
selected by
 
Best answer

SharePoint 2019: Count Items based on Specific Content Type in SharePoint Event Receiver

To get the item count in a SharePoint event receiver based on a specific content type and a condition, you can use a CAML query to filter items in the list.

<Where>
    <Eq>
        <FieldRef Name="ContentType" />
        <Value Type="Text">YourContentTypeName</Value>
    </Eq>
</Where>

Here's an example of how to implement this in your SharePoint event receiver:

using Microsoft.SharePoint;

public override int ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);

    SPList list = properties.List;

    // Define the CAML query to filter by content type 
    SPQuery query = new SPQuery
    {
        Query = @"
            <Where>
                   <Eq>
                        <FieldRef Name='ContentType' />
                         <Value Type='Text'>YourContentTypeName</Value>
                   </Eq>
             </Where>"
    };

    // Execute the query
    SPListItemCollection items = list.GetItems(query);

    // Get the count of the filtered items
    int itemCount = items.Count;
    return itemCount;
}
If you don’t ask, the answer is always NO!
...