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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jan 11, 2018 at 6:04

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;
answered Jan 11, 2018 at 16:37
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.

answered Jan 11, 2018 at 10:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.