现在需要对已有的要素图层添加字段,尝试以下代码:
IFeatureClass pFc= ((IFeatureLayer)lyrRec).FeatureClass;
IFieldsEdit fldsE = pFc.Fields as IFieldsEdit;
IField fld = new FieldClass();
IFieldEdit2 fldE = fld as IFieldEdit2;
fldE.Type_2 = esriFieldType.esriFieldTypeString;
fldE.Name_2 = "XXX";
ic.AddField(fld);
int idTest = gpsFc.Fields.FindField("XXX");
IFieldsEdit fldsE = pFc.Fields as IFieldsEdit;
IField fld = new FieldClass();
IFieldEdit2 fldE = fld as IFieldEdit2;
fldE.Type_2 = esriFieldType.esriFieldTypeString;
fldE.Name_2 = "XXX";
ic.AddField(fld);
int idTest = gpsFc.Fields.FindField("XXX");
调试跟踪,发现IdTest不等于-1 说明执行成功,但是再次启动发现字段未成功添加到要素集
查看帮助 ,对已存在的要素集添加字段 需要用到IClass
IFeatureClass pFc= ((IFeatureLayer)lyrRec).FeatureClass;
IClass pClass=pFc as IClass;
IFieldsEdit fldsE = pFc.Fields as IFieldsEdit;
IField fld = new FieldClass();
IFieldEdit2 fldE = fld as IFieldEdit2;
fldE.Type_2 = esriFieldType.esriFieldTypeString;
fldE.Name_2 = "XXX";
pClass.AddField(fld);
IFieldsEdit fldsE = pFc.Fields as IFieldsEdit;
IField fld = new FieldClass();
IFieldEdit2 fldE = fld as IFieldEdit2;
fldE.Type_2 = esriFieldType.esriFieldTypeString;
fldE.Name_2 = "XXX";
pClass.AddField(fld);
再次执行 成功!
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.
意思就是说如果修改的是当前已经存在的表或者要数类的字段,那么你就使用IClass::AddField方法生成字段
意思就是说如果修改的是当前已经存在的表或者要数类的字段,那么你就使用IClass::AddField方法生成字段
新建要素集则不会出现这种情况