Monday, June 04, 2007

Why isn't there a default value for lookup fields?

Oh, lookup fields, how I hate you.
I just realized that it is not possible in the user inteface to set a default value for a lookup field. Is it that hard to do an interface that will show the user creating the field the options from the looked-up list and allow him to select a default value?
Apperantly it is. I guess Microsoft were worried about what happens if someone deletes the looked-up value.

Not content with my findings, I tried looking in the object model and discovered that you can set up a default value for a lookup field using the following code:

SPList docs = w.Lists["Documents"];
SPFieldLookup fl = (SPFieldLookup)docs.Fields["City"];
fl.DefaultValue = "1;#Mexico City";

I will add this option to my Utility Pack when possible.

Using the above code solves the issue almost totaly. When you use the web interface to add a list item or upload a document, the default value comes up in the lookup box. However (and this is the big one), from the office applications (both 2003 and 2007) the default value is ignored and the lookup box always begins at the "blank" option.

Should I waste one of my MSDN support calls on this and ask MS for a fix? or should I just learn to live with it?


Anonymous said...

Thank you for the simple code sample, I'm fairly sure that we'll try to implement some way to set the default value on our site (in due time).

It's a pain.

Incidentally did you check what happens if the default value (set through code) has been deleted from the lookup list?

Anonymous said...

Make the Lookup field required
The Lookup will have the first value prepopulated

Anonymous said...

@anonymous: having the first value prepopulated is not a nice thing. If the field is an important information and people just go saving those items mit the first value - that really doesn't help.

Anonymous said...


I solved this problem by attaching a workflow to the list. The workflow will populate all the fields with the default values, if nothing is selected.

But this means you have to relax the "requierd" constrain on the field, and hope noone messes with your workflows...

I really also would like a more simple option...

TCison said...

Can you please tell me where to put the code referenced?

Unknown said...

Alternative solution: No code required and supports multi-value lookups.