Thursday, January 12, 2012

SPQuery LookUpFields

"UserDirectory” is the Lookup field for the following actions-
Adding a Lookup Item -
SPListItem listItem = myList.Items[0];
listItem["UserDirectory"] = new SPFieldLookupValue(16, “Details”); // Adding Detailsas text and 16 as ID
listItem.Update();
Retrieving Lookup field for an item-
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem["UserDirectory"].ToString());
string lookUpValue = lookupFieldText .LookupValue;
Updating Lookup field for an item -
SPListItem listItem = myList.Items[0];
SPFieldLookupValue lookupFieldText = new SPFieldLookupValue(listItem ["UserDirectory"].ToString());
lookupFieldText .LookupValue = 17; -> updates the value of the Lookup field for listItem
Retrieving all the values in the Lookup Field -
DropDownList res = new DropDownList();
SPWeb web = SPControl.GetContextWeb(Context);
web = web.ParentWeb;
SPLookupField myLookup = (SPLookupField)web.Fields[str];
SPSite site = web.Site;
SPWeb lookupWeb = site.AllWebs[myLookup.LookupWebId];
SPList lookupList = lookupWeb.Lists[myLookup.LookupList];
foreach(SPListItem lookupItem in lookupList.Items)
{
res.Items.Add(lookupItem[myLookup.LookupField];
}

Finally, SPquery for Lookup field by ID in sharepoint -
<Query>
<Where>
<Eq>
<FieldRef Name='UserDirectory' LookupId=’TRUE’ />
<Value Type=’Lookup’>16</Value>
</Eq>
</Where>
</Query>

No comments:

Post a Comment