To execute row count SQL SPQuery against SPList Item – Use of GetRowCountByField() method

December 12th, 2009 | Categories: Customization, SharePoint, Solutions, WSS 3.0 | Tags: , , ,

Today, I’m going to demonstrate one useful and simple custom method against SPList object which could be reusable in other SharePoint applications. The objective is to verify whether any item is exist in the existing SharePoint list. And if the item is not exist in the SharePoint list, let an entry of the new inserted ListItem into that list.

If we sync our objective with SQL, the SQL logic would be: SELECT Count(FieldName) FROM SPList WHERE FieldName=’value’.
Using SPList or SPListItem objects, we are not supposed to implement the same using existing method and properties.  So let’s start to create the method GetRowCountByField() where we can pass the parameter in some dynamic nature. Below the detais of the parameter objects. Please note, while passing the filedName, we need to pass the internal filed name of the SPList object.
_ReferList: SPList object. This GetRowCountByField() method will be execute the query statement on top of this List object.

FieldInternalName:    SPList object’s field internal name.

FieldType: SPList object’s field type i.e. CHOICE/Number/String etc.

FieldValue: Simple value of that field which is using in WHERE clause in the query object.

Method: GetRowCountByField()

private int GetRowCountByField(SPList _ReferList, string FieldInternalName, string FieldType, string FieldValue)

{

int RowCount = 0;

SPQuery _SPQuery = new SPQuery();

_SPQuery.Query = “<Where><Eq><FieldRef Name=’” + FieldInternalName + “‘/>” + “<Value Type=’” + FieldType + “‘>” + FieldValue + “</Value></Eq></Where>”;

RowCount = _ReferList.GetItems(_SPQuery).Count;

return RowCount;

}

I have used the simple SPQuery object and pass the variables. Very simple approch to get the rowcount.
Here the details below how to call this function and pass the required parameters.

int RefIDCount = 0;

RefIDCount = GetRowCountByField(_SPList, _SPList.Fields["RefID"].InternalName, _SPList.Fields["RefID"].FieldValueType.ToString(), RefItemID.ToString());

Happy Coding :)

No comments yet.