Thursday, March 18, 2010

Create a FeatureClass for Points with Additional Fields in ArcObjects

Just a code snippet for creating a feature class with points. It took me a while to figure out how to change from the default polygon to points.  The key is to change the IGeometryDef before calling CreateFeatureClass.
private IFeatureClass CreatePointsFeatureClassWithFields(String featureClassName,IFeatureWorkspace featureWorkspace)
{
// Instantiate a feature class description to get the required fields.
IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
IObjectClassDescription ocDescription = (IObjectClassDescription)
fcDescription;
IFields fields = ocDescription.RequiredFields;
IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

// Add a Name text field to the required fields.
IField field = new FieldClass();
IFieldEdit fieldEdit = (IFieldEdit)field;
fieldEdit.Name_2 = "LOI";
fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
fieldsEdit.AddField(field);

//change the shape field from polygon to points
int lGeomIndex = 1; //SHAPE field
IField pField = null;
IGeometryDef pGeometryDef;

pField = fields.get_Field(lGeomIndex); //get the shape field
pGeometryDef = pField.GeometryDef;
IGeometryDefEdit edit = (IGeometryDefEdit)pGeometryDef;
edit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //change it to points
edit.SpatialReference_2 = axMapControl1.Map.SpatialReference; //set the spatial ref

// Use IFieldChecker to create a validated fields collection.
IFieldChecker fieldChecker = new FieldCheckerClass();
IEnumFieldError enumFieldError = null;
IFields validatedFields = null;
fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

// The enumFieldError enumerator can be inspected at this point to determine
// which fields were modified during validation
// Create the feature class.
IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
(featureClassName, validatedFields, ocDescription.InstanceCLSID,
ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple,
fcDescription.ShapeFieldName, "");

return featureClass;
}

No comments:

Post a Comment