how to add a  field  ,then set value

687
4
10-10-2013 06:47 AM
yanli
by
New Contributor II

//*****Add a Field
 IField2 pField = new Field() as IField2;
                IFieldEdit2 pFieldEdit = pField as IFieldEdit2;
                pFieldEdit.Name_2 = "BldCoding2";
                pFieldEdit.AliasName_2 = "BldCoding2";
                //pFieldEdit.Length_2 = 3;
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                pFieldEdit.DefaultValue_2 = "1";
                fcBiuding.AddField(pField);

//*****Then get the index of field

IEnumFeature pEnumFeature = ConstDef.m_Editor.EditSelection;
 IFeature pBuildingFeature = null;
                IFeatureCursor pFeaCur = null;
while ((pBuildingFeature = pEnumFeature.Next()) != null)
{
   int i = pBuildingFeature.Fields.FindField("BldCoding2");//  here  is Error ,i=-1

}
                  


why  I can't  get  the index  of Field???
0 Kudos
4 Replies
AlexanderGray
Occasional Contributor III
This is from the IFieldsEdit.AddField help section:
"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."
0 Kudos
JohnStephens
Occasional Contributor
You might want to make sure that a schema lock isn't preventing you from adding the field:

public void AddFieldToFeatureClass(IFeatureClass featureClass, IField field)
{
  ISchemaLock schemaLock = (ISchemaLock)featureClass;

  try
  {
    // A try block is necessary, as an exclusive lock may not be available.
    schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);

    // Add the field.
    featureClass.AddField(field);
  }
  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);
  }
}
0 Kudos
DuncanHornby
MVP Notable Contributor
Not sure why its failing, may be some schema not refreshing? Anyway I would suggest after your line


fcBiuding.AddField(pField);


get the index position then using something like this (this is VB)


i = fcBiuding.FindField("BldCoding2")


and use that in your subsequent code.
0 Kudos
NeilClemmons
Regular Contributor III
Since you're getting the feature you want to edit from the editor's feature selection I'm assuming you're running this code inside of an edit session.  If so, you shouldn't be adding/deleting fields during an edit session.  Add the field before you start editing.
0 Kudos