這篇文章給出實現屬性表功能的具體步驟,之後再對這些步驟中的代碼進行分析。
環境準備
- 拖動TOCControl、MapControl控件到Form窗體上,然後拖動ContextMenuStrip控件至TOCControl上。
TOCControl控件的OnMouseDown事件
如果要使用屬性表功能,首先應該保證鼠標點擊在TOCControl上的圖層,其次應該保證是使用鼠標右鍵點擊的。實現這些判斷的代碼如下:
這裏的TOCControl.HitTest() 方法將鼠標點擊位置的X,Y,元素類型,地圖,圖層等一系列值都付給參數。
private void axTOCControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e)
{
if (e.button == 2)
{
IFeatureLayer pTocFeatureLayer = null;
esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
IBasicMap pMap = null; object unk = null;
object data = null; ILayer pLayer = null;
axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pMap, ref pLayer, ref unk, ref data);
pTocFeatureLayer = pLayer as IFeatureLayer;
if (pItem == esriTOCControlItem.esriTOCControlItemLayer && pTocFeatureLayer != null)
{
contextMenuStrip1.Show(Control.MousePosition);
}
}
}
查看圖層屬性表
初始化屬性表到 DataGridView 中,將這個過程封裝到InitUi方法中
在這個方法中,主要是設置 DataGridView 的數據源 ,其數據源屬性 DataSource 應該爲 DataTable 接口 ,該接口通過 DataTable.Columns.Add() 和 DataTable.Rows.Add() 來添加行與列。
public void InitUI()
{
IFeature pFeature = null;
DataTable pFeatDT = new DataTable();
DataRow pDataRow = null;
DataColumn pDataCol = null;
IField pField = null;
for(int i=0;i<_currentFeatureLayer.FeatureClass.Fields.FieldCount;i++)
{
pDataCol = new DataColumn();
pField = _currentFeatureLayer.FeatureClass.Fields.get_Field(i);
pDataCol.ColumnName = pField.AliasName; //獲取字段名作爲列標題
pDataCol.DataType = Type.GetType("System.Object");//定義列字段類型
pFeatDT.Columns.Add(pDataCol); //在數據表中添加字段信息
}
IFeatureCursor pFeatureCursor = _curFeatureLayer.Search(null, true);
pFeature = pFeatureCursor.NextFeature();
while (pFeature != null)
{
pDataRow = pFeatDT.NewRow();
//獲取字段屬性
for (int k = 0; k < pFeatDT.Columns.Count; k++)
{
pDataRow[k] = pFeature.get_Value(k);
}
pFeatDT.Rows.Add(pDataRow); //在數據表中添加字段屬性信息
pFeature = pFeatureCursor.NextFeature();
}
//釋放指針
System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
//dataGridAttribute.BeginInit();
dataGridAttribute.DataSource = pFeatDT;
}