Here's a function to find the lookup ID from the lookup table:
public static int GetLookupIDFromList(SPWeb web, string strListName, string strLookupColumnName, string strLookupValue)
{
try
{
SPList list = web.Lists[strListName];
string strCAMLQuery = "<Where><Eq><FieldRef Name='"+strLookupColumnName+"' /><Value Type='Text'>"+ System.Web.HttpContext.Current.Server.HtmlEncode(strLookupValue)+"</Value></Eq></Where>";
//If you are developing console application, use
// System.Web.HttpUtility.HtmlEncode(strLookupValue) instead of
//System.Web.HttpContext.Current.Server.HtmlEncode(strLookupValue)
SPQuery query = new SPQuery();
query.Query = strCAMLQuery;
query.ViewFields = string.Concat(
"<FieldRef Name='ID' />",
"<FieldRef Name='"+strLookupColumnName+"' />");
SPListItemCollection items=list.GetItems(query);
if (items.Count > 0)
{
int iRet = items[0].ID;
return iRet;
}
else
{
return 0;
}
}
catch (Exception ex)
{
return 0;
}
}
Here is a sample of how to use the function:
using (SPSite site = new SPSite("http://yoursite/web"))
{
using (SPWeb web=site.OpenWeb())
{
SPList list=web.Lists["ListToUpdate"];
SPListItem item =list.AddItem();
string strLookupValue = "Lookup Value";
int LookupID= GetLookupIDFromList(web, "LookupListName", "Title", strLookupValue);
if (LookupID> 0)
{
SPFieldLookupValue spflv = new SPFieldLookupValue(LookupID,strLookupValue);
//spflv.LookupId = LookupID;
item["LookupFieldName"] = spflv;
item.Update();
}
else
{
strRet += "Lookup value [" + strLookupValue+ "] not found.<br />";
}
}
}