Tuesday, 20 March 2007

How to add a User Information lookup field with code

One of our developers asked me a question about adding a lookup field to the "User information" list with code. The "Add" method of SPFieldCollection wants a Guid for the destination list, but the "User information" list is not a SharePoint list. The solution is to use the "AddFieldAsXML" and submit a field XML instead.

SPWeb web = GetContextWeb(Current) 'Or whatever method used to acquire this object

SPList list = web.Lists[<listname>];

list.Fields.AddFieldAsXml("<Field Type="User" List="UserInfo" ShowField="Title" DisplayName="<FIELDNAME>" Name="<FIELDNAME>" />");


Verified for: WSS v2, SPPS 2003