Programmatically getting the SPField object you just added
When you add an SPField to an SPList programmatically using the SharePoint Object Model you can get the SPField object representing the newly added field via SPList.Fields[string displayName]. But this assumes that no other field with the same display name as the newly added SPField exists in the SPList.
The work around is listed below:
Guid fieldGuid = Guid.NewGuid();
string newFieldCAML = "<Field Type="Text" DisplayName="MyNewField" ID="+fieldGuid+"/>";
splist.Fields.AddFieldAsXml(newFieldCAML, false, SPAddFieldOptions.AddFieldInternalNameHint);
SPField newField = spList.Fields[fieldGuid];
You can use the AddFieldAsXml to add the new SPField. It takes a CAML string as a parameter in which you can specify your own Guid. Later you can use this Guid to retrieve the SPField you just added.
What about using another approach for adding the new field to the list:
SPField someField = myList.Fields.CreateNewField(“Text”, “SomeField”);
myList.Fields.Add(someField );
In this way we get the field reference immediately.
Hi Lubo,
The code sample you have posted is actually what I tried before discovering the xml method. Unfortunately, that method is very misleading. It does not do what you think it does. It does not return a reference of the SPField you just added. I know it is very silly but we found that Microsoft were simply using the SPField object to pass in the arguments rather than returning a proper SPField.
Please refer to this post:
http://jasear.wordpress.com/2009/04/03/sharepoint-issues-and-work-arounds/