(1)首先,我们创建 frmAttribute 类,即存储 属性信息 的对话框
private AxMapControl m_Mapctr;
private ILayer m_pLyr;
public frmAttribute(AxMapControl pMapCtr,ILayer pLyr) //该类创建时,接受参数 "所在地图(pMapCtr)","所在图层(pLyr)"
{
InitializeComponent();
m_Mapctr = pMapCtr;
m_pLyr = pLyr;
}
private void frmAttribute_Load(object sender, EventArgs e)
{
try
{
ILayer pLayer;
pLayer = m_pLyr;
IFeatureLayer pFLayer = pLayer as IFeatureLayer;
IFeatureClass pFC = pFLayer.FeatureClass;
ILayerFields pLayerFields = pFLayer as ILayerFields;
DataSet ds = new DataSet("dsTest");
DataTable dt = new DataTable(pFLayer.Name);
//获取列名
DataColumn dc = null;
for (int i = 0; i < pLayerFields.FieldCount; i++)
{
dc = new DataColumn(pLayerFields.get_Field(i).Name);
dt.Columns.Add(dc);
dc = null;
}
//获取属性表
IFeatureCursor pFCursor = pFC.Search(null, false);
IFeature pFeature = pFCursor.NextFeature();
while (pFeature != null)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < pLayerFields.FieldCount; j++)
{
if (pLayerFields.FindField(pFC.ShapeFieldName) == j)
{
dr[j] = pFC.ShapeType.ToString();
}
else
{
dr[j] = pFeature.get_Value(j).ToString();
}
}
dt.Rows.Add(dr);
pFeature = pFCursor.NextFeature();
}
//显示信息
dataGridView1.DataSource = dt;
}
catch(Exception exception)
{
MessageBox.Show("读取属性表失败:" + exception.Message);
}
}
(2) TOC 的右键菜单弹出时,记录选择的信息:
//为了配合toc右键菜单
private esriTOCControlItem toccItem = esriTOCControlItem.esriTOCControlItemNone;
private IBasicMap pBasicMap = null;
private ILayer pLayer = null;
//点击toc的图层时弹出右键菜单
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
{
object unk = null;
object data = null;
if (e.button == 2)
{
//这个函数最为关键,它找到了鼠标点击 "位置(e.x , e.x.y)" "图层(pLayer)" "类型(toccItem )"
axTOCControl1.HitTest(e.x, e.y, ref toccItem, ref pBasicMap, ref pLayer, ref unk, ref data);
if (toccItem == esriTOCControlItem.esriTOCControlItemLayer)
{
pFLayer = pLayer as IFeatureLayer;
pFC = pFLayer.FeatureClass;
contextMenuStrip2.Show(axTOCControl1, new System.Drawing.Point(e.x, e.y));
}
else if (toccItem == esriTOCControlItem.esriTOCControlItemMap)
{
contextMenuStrip2.Show(axTOCControl1, new System.Drawing.Point(e.x, e.y));
}
}
}
补充:private esriTOCControlItem toccItem = esriTOCControlItem.esriTOCControlItemNone;
这里的 toccItem 有很多类型: esriTOCControlItemHeading(标题处) , esriTOCControlItemMap(地图名称处) ,
esriTOCControlItemLayer(图层名称处) , esriTOCControlItemLegendClass(图层图例处) ,
esriTOCControlItemNone(TOC中heading,map,layer,legend之外所剩余的空白区域)
(3)最后一步,在 Form1 中创建 frmAttribute 实例:
private void 属性ToolStripMenuItem_Click(object sender, EventArgs e)//在Toc上打开属性窗口
{
frmAttribute frm = new frmAttribute(axMapControl1,pLayer);
frm.ShowDialog();
}