开发者

Adding SPFieldLookup to a list programmatically?

I added a SPFieldLookup field to a list programmatically.

When I checked my list view I found that the lookup field is as if I added it from the user inerface without specifying that it is linked to item.

Is there a method to force the lookupfield to be linked 开发者_StackOverflowto item programmatically?


If you are provisioning both the list where the SPFieldLookup field is in, and the target list you will have a problem. Because the SPFieldLookup field needs to assign the target list by its GUID, which is created dynamically when the feature is activated. And you can't define this value in your field definition, since it doesn't exists yet.

The solution to this problem is provisioning both the "source" list and the target list normally, except the SPFieldLookup field in the source list.
Then, in the feature activated event, you add this lookup field programmatically, which could now be done since you have (or at least can find out) the GUID for the target list.


This is a nice snippet I saw and will like to share Let us assume we have two list aList and bList already created. Requirement is to create a lookup column in aList which will look up values in bList.

 SPList aList = web.Lists["aList"];
 SPList bList = web.Lists["bList"];
 aList.Fields.AddLookup("Lookup", bList.ID, false);
 SPFieldLookup fldLookup = aList.Fields["Lookup"] as SPFieldLookup;
 fldLookup.LookupField = bList.Fields[SPBuiltInFieldId.Title].InternalName;
 fldLookup.Update();


Did you fill all the needed properties (LookupField, LookupWebId and maybe also LookupList) and Update() the field afterwards?

Perhaps http://www.alexbruett.net/?p=153 will help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜