I'm trying to add a GUID field programmatically to an existing FeatureClass using ArcObjects.
Here is my code:
ISchemaLock schemaLock = (ISchemaLock)ipFC;
try
{
// A try block is necessary, as an exclusive lock may not be available.
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
//Ajout d'un champ GUID
IFieldsEdit pNewFieldsEdit = (IFieldsEdit)ipFC.Fields;
IField guidField = new FieldClass();
IFieldEdit guidFieldEdit = (IFieldEdit)guidField;
guidFieldEdit.Name_2 = "OldGlobalID";
guidFieldEdit.Type_2 = esriFieldType.esriFieldTypeGUID;
guidFieldEdit.DefaultValue_2 = null;
guidFieldEdit.IsNullable_2 = true;
pNewFieldsEdit.AddField(guidField);
}
catch (Exception exc)
{
// Handle this in a way appropriate to your application.
Console.WriteLine(exc.Message);
}
finally
{
// Set the lock to shared, whether or not an error occurred.
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
Everything seems to work (no error) and it's based on an documentation example. Unfortunately, when I click on the feature class in ArcCatalog and open the table preview, I have this message showing:
enter image description here
Also, the table open in the preview, but it's all empty (header and row) with 308 records(the correct number of row in the feature class). What am I doing wrong?
EDIT
If I check the properties of my feature class, the new field seems to be there:
enter image description here
But the preview looks like this right after the error message...:
enter image description here
Any ideas?
EDIT 2
I discovered that when I restart ArcCatalog and go back in the properties, the new field is gone and there is no problem opening the table preview, but the new field is nowhere to be found. Maybe there is a function to "Save" everything after the field has been added?
1 Answer 1
If you take a closer look at the documentation example, you'll notice that they use the IFeatureClass::AddField function
IField guidField = new FieldClass();
IFieldEdit guidFieldEdit = (IFieldEdit)guidField;
guidFieldEdit.Name_2 = "OldGlobalID";
guidFieldEdit.Type_2 = esriFieldType.esriFieldTypeGUID;
guidFieldEdit.DefaultValue_2 = null;
guidFieldEdit.IsNullable_2 = true;
ipFC.AddField(guidField);
In your case, you were using the feature class Fields collection to add you field (IFieldsEdit.AddField method). Which is not supported, see the Remarks section in this article.
Remarks
AddField is used when creating a fields collection and cannot be used to insert a field into a fields collection belonging to an existing table. To add a field to an existing object class, use the IClass::AddField method.
Explore related questions
See similar questions with these tags.
AddField
method when you perform it? For example,FDO_E_NO_SCHEMA_LICENSE
can be returned on failure.