Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.



I've created a lookup field programmatically in the featureactivated method. This is the code snippet.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
  using (SPWeb web = (SPWeb)properties.Feature.Parent)
  {
    SPList destinationList = web.Lists.TryGetList("Participating Artists");
    SPList sourceList = web.ParentWeb.Lists.TryGetList("artistlist");
    destinationList.Fields.AddLookup("Artist", sourceList.ID, false);

    SPFieldLookup lkp = (SPFieldLookup)destinationList.Fields["Artist"];
    lkp.LookupField = "Title";
    lkp.Update();
  }
}

The sourcelist is on the parent page of where the feature is activated. Everyting works fine. The only problem I'm having is that no item is getting "looked up" in the destination list when I'm creating a new listitem. The lookupfield remains empty even if the sourcelist has items in it.

This is how the sourcelist looks like:

elements.xml

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!-- Do not change the value of the Name attribute below. If it does not match the folder name of the List project item, an error will occur when the project is run. -->
    <ListTemplate
        Name="artist"
        Type="10000"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="artistlist"
        Description="My List Definition"
        Image="/_layouts/15/images/itgen.png"/>
</Elements>

And the

schema.xml

<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="artistlist" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/artistlist" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
    <MetaData>
        <ContentTypes>
            <ContentType ID="0x01002b8b73e5d4d94e75995b6af193be129e" Name="ListFieldsContentType">
                <FieldRefs>
                    <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" />
                </FieldRefs>
            </ContentType>
            <ContentTypeRef ID="0x01">
                <Folder TargetName="Item" />
            </ContentTypeRef>
            <ContentTypeRef ID="0x0120" />
        </ContentTypes>
        <Fields>
            <Field ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Type="Text" Name="Title" DisplayName="Artist" Required="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Title" MaxLength="255" />
        </Fields>
        <Views>
            <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
                <Toolbar Type="Standard" />
                <XslLink Default="TRUE">main.xsl</XslLink>
                <RowLimit Paged="TRUE">30</RowLimit>
                <ViewFields>
                    <FieldRef Name="LinkTitleNoMenu"></FieldRef>
                </ViewFields>
                <Query>
                    <OrderBy>
                        <FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
                    </OrderBy>
                </Query>
                <ParameterBindings>
                    <ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
                    <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
                    <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
                </ParameterBindings>
            </View>
            <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/15/images/generic.png?rev=23" Url="AllItems.aspx">
                <Toolbar Type="Standard" />
                <XslLink Default="TRUE">main.xsl</XslLink>
                <JSLink>clienttemplates.js</JSLink>
                <RowLimit Paged="TRUE">30</RowLimit>
                <ViewFields>
                    <FieldRef Name="LinkTitle"></FieldRef>
                </ViewFields>
                <Query>
                    <OrderBy>
                        <FieldRef Name="ID"></FieldRef>
                    </OrderBy>
                </Query>
                <ParameterBindings>
                    <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
                    <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
                </ParameterBindings>
            </View>
        </Views>
        <Forms>
            <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
            <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
            <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
        </Forms>
    </MetaData>
</List>
share|improve this question
add comment

3 Answers 3

up vote 2 down vote accepted

I would recommend using the declarative approach to provision your lookup, especially since it looks like your parent list is deployed this way. There is a trick to doing this, though, in that your lookup must be declared after the list instance representing your parent list. I handle this by provisioning my lookups directly inline with the list instance, like this:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="Clients" 
            OnQuickLaunch="TRUE" 
            TemplateType="10000" 
            Url="Lists/Clients" 
            Description="My List Instance">

  </ListInstance>

<Field Name="Client" 
     DisplayName="Client" 
     ID="{BA0F3BCC-430B-4388-922B-A29E96364E61}" 
     Type="Lookup" 
     List="Lists/Clients" 
     ShowField="Title" 
     Group="_DMG Site Columns" >
</Field>
</Elements>

...and if I may, and since I've seen several people struggle with this, I wrote a quick blog post with a little more detail on the topic.

share|improve this answer
add comment

I think you forget to specify some information on your code behind.

Take a look at this solution: http://salvatoredifaziosharepoint.blogspot.co.uk/2012/07/sharepoint-2010-create-content-type.html

BTW in the Field specification I wrote something like this:

<Field ID="{2AAD1044-89E9-4C88-8234-424A4B739C1C}" Name="LookupToList" DisplayName="LookupToList" StaticName="LookupToList" Type ="Lookup" Required="TRUE" Group="Custom Columns" Overwrite="TRUE" WebId="~sitecollection" EnforceUniqueValues="FALSE"   List="Lists/MyList" SourceID="http://schemas.microsoft.com/sharepoint/v3" ShowField="MyLookupField" />
share|improve this answer
add comment

I suppose that you do not have your lookup items because when your list is created it does not know yet where to get columns from (source list does not exists).

What we usually do is moving XML declaration to event receiver when feature is activated. In this event receiver you should specify root web and list IDs to get it work. Here is the example:

var site = new SPSite((properties.Feature.Parent as SPSite).ID);

SPSecurity.RunWithElevatedPrivileges(delegate
{
    SPList referencedList = site.RootWeb.Lists[Lists.TestimonialsList];
    SPContentType myContentType = site.RootWeb.ContentTypes[ContentTypes.ExpertiseContentType];

    SPField _lookup = site.RootWeb.Fields[new Guid("{2DC1E1AF-F5C5-490A-ABCF-B7F1E8834C2F}")];
    if (_lookup == null)
    {
       site.RootWeb.Fields.AddFieldAsXml(
       @"<Field
       ID='{2DC1E1AF-F5C5-490A-ABCF-B7F1E8834C2F}'
       Name='Name'
       StaticName='Name'
       DisplayName='Display name'
       Type='Lookup'
       List='" + referencedList.ID + @"'
       ShowField='Title'
       UnlimitedLengthInDocumentLibrary='TRUE'
       Group='your group'
       SourceID='http://schemas.microsoft.com/sharepoint/v3'
       Mult='TRUE'
       WebId='" + site.RootWeb.ID.ToString() + @"'
       Overwrite='TRUE'
       Required='FALSE'>
       </Field>");
    }

    SPFieldLink myFIeldLink = new SPFieldLink(site.RootWeb.Fields[Fields.TestimonialReferenceField]);
    myContentType.FieldLinks.Add(myFIeldLink);
    myContentType.Update(true);
});        
site.Dispose();

When do this do not forget that you do not need anymore to have this XML declaration nor in your fields, nor in content type or list schema.

Hope it helps you,

Andrew

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.