Wednesday, July 9, 2008

Setting the "default" value for a Lookup Column in SharePoint

For some reason, you can set the default for lookup fields, after they are created, on most other field types in SharePoint, but the Lookup Column does not have a default value. What?!!! Well, after scouring the web, I got some bits and pieces, but then I found a post by Ishai Sagi who talked about this very issue.

Basically, you have to write some .NET code and shove it in a web part (I piggy-backed my code to a button of an existing web part and re-GAC'd it -- of course you will want to remove the code and GAC the dll again after you are done). Here's the code you want to use:

web = SPContext.Current.Web;
SPList docs = web.Lists["MyCustomList"];
SPFieldLookup f = (SPFieldLookup)docs.Fields["Email Address"];
f.DefaultValue = "3;#support@jwc3.net";
f.Update();
Hope that helps.