when you use SharePoint 2010 you may need to create cross-site lookup field. That is problem because SP 2010 doesn't natively support this kind of field. But as always there is some work around :) Even though the work around doesn't involve GUI, it isn't difficult at all.
Here is sample of code how you can easily create cross-site lookup field:
//Add new column to list and ensure
cross side lookup
try
{
//Web contains list where a new column is required
SPSite currentSite = new
SPSite("https://server/siteContainsListWithRequiredNewColumn");
SPWeb currentWeb = currentSite.OpenWeb();
SPList currentlist = currentWeb.Lists["Some List"];
//Web that holds data for lookup field
SPSite lookupSite = new
SPSite("https://server/lookupSite");
SPWeb lookupWeb = lookupSite.OpenWeb();
SPList lookupList = lookupWeb.Lists["Lookup list"];
string fieldXML = "<Field
DisplayName='Name of new column' Type='Lookup' Required='TRUE' List='"
+ lookupList.ID + "' WebId='" +
lookupWeb.ID + "' Name='LookupField'
ShowField='" + "Viewed field"
+ "' />";
//Add new column to the list
currentlist.Fields.AddFieldAsXml(fieldXML,
true, SPAddFieldOptions.AddFieldToDefaultView);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
After you you add cross-site field I would recommend you to open column properties although you don't need to change anything. It happened to me that newly added column doesn't work properly and re-saving those column properties solved problem.
Happy codding....
No comments:
Post a Comment