前些日子做了一個數據庫的修改工作,要為數據添加字段,數據為Geodatabase類型,里面有90多個圖層,每個圖層添加6個字段,一共要做2個小時左右,而且效率比較低,容易出錯,因此想到了通過程序來解決。
實現如下,首先先建立程序主窗體,包括TocControl,AxMapControl和ToolBarControl,設置好他們之間的Buddy屬性,在ToolBarControl中添加基本工具(包含數據加載工具,用於加載操作數據)。
地圖加載進來,就可以對圖層進行循環處理添加字段了。
主要代碼如下:
public ILayer pLayer; public IFeatureLayerpFLayer; public IFeatureClasspFC; public ILayerFieldspLayerFields; DataTable dt = new DataTable(); private voidbtnAdd_Click(object sender, EventArgs e) { if(axMapControl1.LayerCount == 0) { MessageBox.Show("請先加載添加字段的圖層!"); return; } //循環所有圖層 for(int i = 0; i < axMapControl1.LayerCount;i++) { try { pLayer =axMapControl1.get_Layer(i); pFLayer = pLayer as IFeatureLayer; pFC = pFLayer.FeatureClass; pLayerFields = pFLayer as ILayerFields; ITablepTable = (ITable)pFC; //刪除原來表中的數據,若不需要可以去除,在數據庫有數據的情況下無法插入非空字段 pTable.DeleteSearchedRows(null); IFieldnewField = new FieldClass(); IFieldEditfieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = "字段名稱"; //數據類型,這里以字符型為例 fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; //字節長度 fieldEdit.Length_2 = 1; //字段是否允許為空 fieldEdit.IsNullable_2 = false; pFC.AddField(newField); } catch(Exception exc) { MessageBox.Show("添加失敗" + exc.Message); } } }
