3

I am trying to add a field to first layer in the map here is my code

ESRI.ArcGIS.Framework.IApplication app = ArcMap.Application;
ESRI.ArcGIS.Framework.IDocument doc = app.Document;
ESRI.ArcGIS.ArcMapUI.IMxDocument mxd = doc as ESRI.ArcGIS.ArcMapUI.IMxDocument;
ESRI.ArcGIS.Carto.IMap map = mxd.FocusMap;
ESRI.ArcGIS.Carto.ILayer lay = map.Layer[0];
ESRI.ArcGIS.Carto.IFeatureLayer flay = lay as ESRI.ArcGIS.Carto.IFeatureLayer;
ESRI.ArcGIS.Geodatabase.IFeatureClass fcls = flay as ESRI.ArcGIS.Geodatabase.IFeatureClass;
ESRI.ArcGIS.Geodatabase.IFieldEdit fld = new ESRI.ArcGIS.Geodatabase.FieldClass();
string nam = "map";
fld.AliasName_2 = nam;
fld.Type_2 = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeString;
fld.Length_2 = 50;
fld.Name_2 = "country name";
fcls.AddField(fld);

It throws a NullReferenceException, where I did do wrong?

2 Answers 2

2
ESRI.ArcGIS.Geodatabase.IFeatureClass fcls = flay as ESRI.ArcGIS.Geodatabase.IFeatureClass;

You went wrong here. An IFeatureLayer cannot be cast to an IFeatureClass. This line should be this:

ESRI.ArcGIS.Geodatabase.IFeatureClass fcls = flay.FeatureClass;
0
2

Field names cannot have spaces in their name, so this line is invalid:

fld.Name_2 = "country name";

The field alias is the human readable name of the field which CAN have spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.