views:

49

answers:

2

I tried setting the defaultvalue property of the field to Guid.NewGuid() but every item created has the same guid so I guess the Guid.NewGuid() is being stored as the default rather than being run each time.

Is the only way to achieve this to add an event handler to the list for OnAdded?

A: 

If you are creating the field through code and setting the field.DefaultValue = Guid.NewGuid(), this will run the Guid.NewGuid() and store the returned Guid as the default It is the equlivant of running the folowing code:

Guid newGuid = Guid.NewGuid();
string newGuidString = newGuid.ToString();
field.DefaultValue = newGuidString;

I dont know of any method you can use to set the field to generate a new Guid on item creation other than using an Event handler.

It should be posable to genrate a random number using the field.DefaultValue = "RANDBETWEEN(10,20)"; but i have not tested this

JC Vivian
+1  A: 

I'm assuming you're using a Single Line of Text field for this. The standard default for such a field is always a constant, you can't assign a variable or function via the object model. All that would do is assign the static result of that particular call of the function.

While text fields can support a calculated default value, it uses the same functions that are in Calculated columns, which do not support random numbers.

Your best bet is to use an Event Handler, I would recommend ItemAdding over ItemAdded as well. You'd be assigning to properties.AfterProperties["fieldname"] instead of field.DefaultValue, of course.

ccomet