[GIS] Adding Field To feature class using ArcObjects and C#

arcobjectscfields-attributes

I want to add a new field to my featureclass.My code for that is:

        public IMxDocument mxDoc;
        public IMap map;
        IFieldEdit2 field = new FieldClass() as IFieldEdit2;
        field.Name_2 = "Parcel_Way";
        field.Type_2 = esriFieldType.esriFieldTypeString;
        field.Length_2 = 50;
        field.DefaultValue_2 = "Parcel";
        IFeatureLayer2 flayer=map.Layer[cmboxLayer2.SelectedIndex] as IFeatureLayer2;
        IFeatureClass featureclass = flayer.FeatureClass;

        try
        {
            featureclass.AddField(field);
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message, ex.Source);
            throw;
        }

Program return this error :
enter image description here

What do i neglecting ?

Best Answer

Adding a field directly in ArcMap may not work if the feature class is included in your mxd.

Usually, before modifying a feature class schema(such as adding a field), you should acquire an exclusive schema lock, to ensure that the feature class is opened only by your code.

Here's an example acquiring a schema lock

// Try to acquire an exclusive schema lock.
ISchemaLock schemaLock = (ISchemaLock)yourFeatureClass;
try
{
    schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);

    // Add your field.
    ...
}
catch (COMException comExc)
{
    // Handle the exception appropriately for the application.
}
finally
{
    // Demote the exclusive lock to a shared lock.
    schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}

In your case, probably that you won't be able to acquire a lock because the feature class you want to lock is already opened in your mxd document.

ArcCatalog may be a better place to add this kind of code.

Related Question