Simple SPQuery throws error
-
09-12-2019 - |
Question
I am trying to pull populate a lookup field using a lookup value without the lookup ID. I am getting the error: "One or more field types are not installed properly. Go to the list settings page to delete these fields." I have the following code:
public static SPFieldLookupValue getLookUpValue(string lookupValue, SPList myList, String LookupField, string LookupSourceField)
{
SPFieldLookup lookUpField = (SPFieldLookup)myList.Fields[LookupField];
SPList lookupSourceList = myList.ParentWeb.Lists.GetList(new Guid(lookUpField.LookupList), false); //ParentWeb.Lists[lookUpField.LookupList];
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name=’{1}’/><Value Type=’Text’>{0}</Value></Eq></Where>", lookupValue, LookupSourceField);
SPListItemCollection listItems = lookupSourceList.GetItems(query);
if (listItems[0] != null)
{
return new SPFieldLookupValue(listItems[0].ID.ToString());
}
return null;
}
I call the code like this:
string LookupValue = null;
if (properties.ListItem["SupplierID"] != null)
{
LookupValue = properties.ListItem["SupplierID"].ToString();
}
string FieldFromWhereToLookup = "sup";
string SourceField = "SupplierID";
SPFieldLookupValue lookupID = getLookUpValue(LookupValue, properties.List, FieldFromWhereToLookup, SourceField);
While stepping through the code, query.Query shows the following:
<Where>
<Eq>
<FieldRef Name=’SupplierID’/>
<Value Type=’Text’>100367</Value>
</Eq>
</Where>
I ensured that lookupSourceList is populated with the correct list. U2U CAMLBuilder shows the following when I build a query using the same list, field, and filter value:
<Where>
<Eq>
<FieldRef Name="SupplierID" />
<Value Type="Text">100367</Value>
</Eq>
</Where>
Solution 2
My single quotes were off.
<Where><Eq><FieldRef Name=’{1}’/><Value Type=’Text’>{0}</Value></Eq></Where>
should have been:
<Where><Eq><FieldRef Name='{1}'/><Value Type='Text'>{0}</Value></Eq></Where>
OTHER TIPS
Double quotes will do as well, like
query.Query = String.Format("<Where><Eq><FieldRef Name=\"{1}\"/><Value Type=\"Text\">{0}</Value></Eq></Where>", lookupValue, LookupSourceField);
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange