I have a list in which there is one column which is of type People or Group with multi allow. I have created Item Adding event receiver in which I am checking the entered people value is already available or not. If it is then I am displaying the error message.
To query the People or Group field I found this solution, I tried it in my code which is as follows:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
SPQuery query = null;
SPList list = properties.List;
int i = 1;
string strUsers = (string)properties.AfterProperties[FieldNames.Manager];
string strQuery = "<Where> <Or>";
SPFieldUserValueCollection newUsers = new SPFieldUserValueCollection(properties.Web, strUsers);
foreach (SPFieldUserValue value in newUsers)
{
SPUser user = null;
if (value.LookupId > 0)
{
user = value.User;
}
else if (value.LookupId < 0)
{
user = properties.Web.EnsureUser(value.LookupValue);
}
if (i % 2 != 0)
{
strQuery += "<Or>";
}
strQuery += "<Includes> <FieldRef Name='" + FieldNames.Manager + "' LookupId='TRUE'/> <Value Type='Integer'>" + user.ID + "</Value></Includes>";
if (i % 2 != 0)
{
strQuery += "</Or>";
}
i++;
}
strQuery += "</Or></Where>";
query = new SPQuery();
query.Query = strQuery;
SPListItemCollection coll = list.GetItems(query); // I am getting error here..
if(coll.Count > 0)
{
properties.ErrorMessage = "Manager is already assigned to other department";
properties.Status = SPEventReceiverStatus.CancelWithError;
}
}
The resultant query generated by my program is:
<Query>
<Where>
<Or>
<Or>
<Includes>
<FieldRef Name='oiplbManager' LookupId='TRUE'/> <Value Type='Integer'>1</Value>
</Includes>
</Or>
<Includes> <FieldRef Name='oiplbManager' LookupId='TRUE'/> <Value Type='Integer'>18</Value>
</Includes>
</Or>
</Where>
</Query>
What am I missing?