/// <summary> /// 删除指定名称的Field /// </summary> /// <param name="featureClass"></param> /// <param name="fieldname"></param> public static void DeletField(IFeatureClass featureClass, string fieldname) { IFields fields = featureClass.Fields; IField field = fields.get_Field(fields.FindField(fieldname)); featureClass.DeleteField(field); }
public static void DeleteFields(string mdbfile, List <StockTable> tables) { IWorkspace workspace = mdbfile.OpenAccessFileWorkSpace(); foreach (var table in tables) { IFeatureClass featureClass = workspace.GetFeatureClass(table.Name); for (var i = 0; i < featureClass.Fields.FieldCount; i++) { IField field = featureClass.Fields.get_Field(i); Console.WriteLine(table.Name + "-" + field.Name); if (Ignores.Any(e => e.ToLower() == field.Name.ToLower()) == false) { if (field.Type == esriFieldType.esriFieldTypeOID || field.Type == esriFieldType.esriFieldTypeGeometry || field.Type == esriFieldType.esriFieldTypeGUID) { continue; } if (table.Fields.Any(e => e.Name.ToLower() == field.Name.ToLower()) == false) { featureClass.DeleteField(field); } } } Marshal.ReleaseComObject(featureClass); } Marshal.ReleaseComObject(workspace); }
private void ToolStripMenuItem_Click(object sender, EventArgs e) { try { IDataset dataset = (IDataset)Variable.pAttributeTableFeatureLayer.FeatureClass; IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)dataset.Workspace; if (workspaceEdit.IsBeingEdited()) { MessageBox.Show("地图处于编辑状态,暂时无法删除字段!"); return; } if (MessageBox.Show(string.Format("确定要删除 {0} 字段吗?", this.columnName), "", MessageBoxButtons.OKCancel) == DialogResult.OK) { IFeatureClass featureClass = Variable.pAttributeTableFeatureLayer.FeatureClass; IFields fields = featureClass.Fields; IField field = fields.get_Field(this.columnIndex); featureClass.DeleteField(field); // 删除字段 dataGridView1.Columns.RemoveAt(this.columnIndex); // 删除列 MessageBox.Show(string.Format("{0} 字段已删除!", this.columnName)); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.ToString(), "异常"); } }
public bool DeleteField() { string strFieldName = cmbfields.Text; if (m_pLayer is IFeatureLayer) { IFeatureLayer featureLayer = m_pLayer as IFeatureLayer; if (featureLayer.FeatureClass == null) { return(false); } IFeatureClass featureClass = featureLayer.FeatureClass; IFields fields = featureLayer.FeatureClass.Fields; int nIndex = fields.FindField(strFieldName); if (nIndex < 0) { return(false); } try { featureClass.DeleteField(fields.get_Field(nIndex)); return(true); } catch (System.Exception ex) { return(false); } } return(false); }
public bool PurePixel2Shp(out string msg) { IFeatureClass pFeatureClass = null; try { string outEnd = System.IO.Path.Combine(BLL.ConstDef.PATH_TEMP, "PurePixel_" + DateTime.Now.ToFileTime().ToString() + ".shp"); if (!BLL.EnviVars.instance.GpExecutor.Raster2Polygon(_Hyper_PurePixel, outEnd, false, out msg)) { return(false); } //字段整理 pFeatureClass = EngineAPI.OpenFeatureClass(outEnd); pFeatureClass.DeleteField(pFeatureClass.Fields.get_Field(0)); IField field = new FieldClass(); IFieldEdit fieldEdit2 = field as IFieldEdit; fieldEdit2.Name_2 = "CLASS_ID"; fieldEdit2.Type_2 = esriFieldType.esriFieldTypeInteger; pFeatureClass.AddField(field); return(true); } catch (Exception ex) { msg = ex.Message; return(false); } }
public static void DeleteField(IFeatureClass featureClass, string fieldName) { int idx = featureClass.FindField(fieldName); if (idx < 0) { return; } IField field = featureClass.Fields.Field[idx]; featureClass.DeleteField(field); }
/// <summary> /// 删除要素类中的字段 /// </summary> public static bool DeleteField(IFeatureClass fc, string fieldName) { bool rbc = false; int fIndex = fc.FindField(fieldName); if (fIndex >= 0) { IField fd = fc.Fields.get_Field(fIndex); fc.DeleteField(fd); rbc = true; } return(rbc); }
//删除字段事件; private void 除字段ToolStripMenuItem_Click(object sender, EventArgs e) { string FieldName_1 = this.dataGridView1.Columns[DataGridiewColumnsIndex].HeaderText; IFeatureLayer pfeaturelayer = layer as IFeatureLayer; IFeatureClass pfeatureclass = pfeaturelayer.FeatureClass; int index = pfeatureclass.FindField(FieldName_1); IFields pfields = pfeatureclass.Fields; IField pfield = pfields.get_Field(index); if (MessageBox.Show("确认删除吗", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { pfeatureclass.DeleteField(pfield); } }
private void button4_Click(object sender, EventArgs e) { //int i = this.dataGridView1.CurrentRow.Index; try { int j = this.dataGridView1.CurrentCell.ColumnIndex; string fieldName = dataGridView1.Columns[j].Name; int index = pFields.FindField(fieldName); IField pField = pFields.get_Field(index); pFeatureClass.DeleteField(pField); dataGridView1.Columns.RemoveAt(j); MessageBox.Show("删除成功"); } catch (Exception ex) { MessageBox.Show("删除失败"); } }
/// <summary> /// 删除要素集合非选中字段 /// </summary> /// <param name="featureClass">要素集合</param> /// <param name="selectFieldName">选中字段名称</param> private static void DeleteFeatureClassFields(IFeatureClass featureClass, List <string> selectFieldName) { int fieldCount = featureClass.Fields.FieldCount; //字段总数 //字段数等于选中字段数,直接返回 if (selectFieldName.Count == fieldCount) { return; } //删除不在表格中的字段 //从大往小进行遍历,因为字段总数会变化 for (int i = fieldCount - 1; i > 0; i--) //保留FID和Shape字段,所以不删除索引为0,1的字段 { IField field = featureClass.Fields.Field[i]; //当前字段 //是选中或只读字段,则跳过 if (IsSelectOrReadonlyField(selectFieldName, field)) { continue; } featureClass.DeleteField(field); } }
private bool TryDeleteAField(IFeatureClass pFeatureClass, string pFieldName) { ISchemaLock tSchemaLock = (ISchemaLock)pFeatureClass; bool successful = false; try { tSchemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); int tDeleteFieldNum = pFeatureClass.Fields.FindField(pFieldName); if (tDeleteFieldNum != -1) { IField tDeleteField = pFeatureClass.Fields.get_Field(tDeleteFieldNum); pFeatureClass.DeleteField(tDeleteField); successful = true; } else { logger.LogMessage(ServerLogger.msgType.debug, "DeleteAField", 8000, "Couldn't find field requested for deletion: " + pFieldName + " from feature class!"); } } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.debug, "DeleteAField", 8000, "Couldn't delete field " + pFieldName + " from feature class! " + ex.Message); } finally { tSchemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } return successful; }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }
private void deleteFieldToolStripMenuItem_Click(object sender, EventArgs e) { string fieldInfo_name = selectNode.Text; string fc_name = selectNode.Parent.Text; string set_name = selectNode.Parent.Parent.Text; myTreeNode node = (myTreeNode)selectNode.Parent.Parent.Parent; IConnectionInfo ci = node.con; IDataSource ds = null; IFeatureDataSet dset = null; IFeatureClass fc = null; try { ds = dsFactory.OpenDataSource(ci); dset = ds.OpenFeatureDataset(set_name); fc = dset.OpenFeatureClass(fc_name); if (fieldInfo_name == "oid") { MessageBox.Show("此字段不支持删除"); return; } if (MessageBox.Show("该操作无法恢复,请确定是否删除字段?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { fc.LockType = gviLockType.gviLockExclusiveSchema; fc.DeleteField(fieldInfo_name); fc.LockType = gviLockType.gviLockSharedSchema; // 从树上删除节点 selectNode.Parent.Nodes.Remove(selectNode); MessageBox.Show("删除成功"); } } catch (COMException comEx) { System.Diagnostics.Trace.WriteLine(comEx.Message); MessageBox.Show("删除失败"); } catch (System.Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); MessageBox.Show("删除失败"); } finally { fc.LockType = gviLockType.gviLockSharedSchema; if (fc != null) { //Marshal.ReleaseComObject(fc); fc = null; } if (dset != null) { //Marshal.ReleaseComObject(dset); dset = null; } if (ds != null) { //Marshal.ReleaseComObject(ds); ds = null; } } }
public void delteField(IFeatureClass featureClass, string fldNm) { ISchemaLock schemaLock = (ISchemaLock)featureClass; try { // A try block is necessary, as an exclusive lock might not be available. schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); int fldIndex = featureClass.FindField(fldNm); featureClass.DeleteField(featureClass.Fields.get_Field(fldIndex)); } catch (Exception exc) { // Handle appropriately for your application. Console.WriteLine(exc.Message); //MessageBox.Show(exc.Message); } finally { // Set the lock to shared, whether or not an error occurred. schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } }
private void CreateField() { if (_editor.EditState != esriEditState.esriStateNotEditing) { MessageBox.Show("Stop Editing First", MB_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (cbo_layers.SelectedIndex < 0) { MessageBox.Show("Select A Layer", MB_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } CustomLayer customLayer = (CustomLayer)cbo_layers.SelectedItem; IFeatureClass FeatureClass = customLayer.FeatureClass(); IFields fields = FeatureClass.Fields; int fieldIndex = _utilitiesArcMap.FindField(FeatureClass, FIELD_NAME); if (fieldIndex > -1) { IField field = FeatureClass.Fields.Field[fieldIndex]; if (field.Type != esriFieldType.esriFieldTypeString) { if (MessageBox.Show("Field exists as wrong field type. It needs to be 'Text' Field. Should I delete and re-create?", MB_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } FeatureClass.DeleteField(field); } else { if (field.Length < 20) { if (MessageBox.Show("Field exists as wrong size. It needs to be at least 20 in length. Should I delete and re-create?", MB_TITLE, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } FeatureClass.DeleteField(field); } else { return; } } } IFieldEdit2 newField = new FieldClass() as IFieldEdit2; newField.Name_2 = FIELD_NAME; newField.Type_2 = esriFieldType.esriFieldTypeString; newField.Length_2 = 20; newField.DefaultValue_2 = "Unchecked"; ISchemaLock schemaLock = (ISchemaLock)FeatureClass; try { schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); FeatureClass.AddField(newField); } catch { MessageBox.Show("Cannot Aquire Exclusive Lock. Did Not Add Field", MB_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } }