If you are trying to use the SharPoint LookupField control you will probably want to explicitly bind it to a list. You can do this in markup by passing the ListId attribute as follows:

SharePoint:LookupField ID="ContactTypeLookup" runat="server" ListId="253C5ECA-D17B-460F-A16F-FEEE749D8B1F" ControlMode="New" FieldName="ContactType" />

But what if you want to bind it to a list by name or set the list id in code? The first thing you might do is remove the ListId attribute in the markup and set the ListId property of the LookupField as so:

ContactTypeLookup.ListId = SPContext.Current.Web.Lists["ContactTypes"].ID;

When you do you will get this lovely error:

image

The problem is that the LookupField control uses the list defined in the ItemContext property (Which is a SPContext object). Using good ole' reflector you will find that this property originates from the base class Microsoft.SharePoint.WebControls.FormComponent. The ItemContext is lazily instantiated when the property is first accessed. At that time it creates a new SPContext based off the value set in the ListId property. Evidentially this property is accessed at some point before the page loads thus instantiating the ItemContext before you have a chance to set the ListId. So setting ListId after that point does no good. What you can do however is give it a new ItemContext based off the list you want as follows:

ContactTypeLookup.ItemContext = SPContext.GetContext(HttpContext.Current, 0, SPContext.Current.Web.Lists["ContactTypes"].ID, SPContext.Current.Web);

And make sure you remove the ListId attribute in the markup:

<SharePoint:LookupField ID="ContactTypeLookup" runat="server" ControlMode="New" FieldName="ContactType" />

That's all there is too it!

image