分析:要显示某一个图层的属性表,首先要将这个图层选中,然后在另外一个Form中将选中的这个图层的属性信息进行显示。
添加一个上下文菜单,添加一个新的Form窗体,在这个新的窗体上添加GridView控件。
1 新建另外一个窗体 Form2
- 首先要定义一个全局变量 ILayer。
- 带参数的构造函数,以便将 ILayer 传递过来。
- 获取属性列表。
ILayer pLayer;
public Form2(ILayer layer)
{
InitializeComponent();
pLayer = layer;
}
private void Form2_Load(object sender, EventArgs e)
{
IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
IFeature pFeature = pFeatureCursor.NextFeature();
IFields pFields = pFeatureClass.Fields;
DataTable pTable = new DataTable();
for (int i = 0; i < pFields.FieldCount; i++) //获取所有列
{
DataColumn pColumn = new DataColumn(pFields.get_Field(i).Name);
pTable.Columns.Add(pColumn);
}
while (pFeature != null)
{
DataRow pRow = pTable.NewRow();
for (int i = 0; i < pFields.FieldCount; i++) //添加每一列的值
{
pRow[i] = pFeature.get_Value(i);
}
pTable.Rows.Add(pRow);
pFeature = pFeatureCursor.NextFeature();
}
dtGridView1.DataSource = pTable;
}
2 建立右键菜单项 (Form1中)
- 判断在什么情况下显示右键菜单。
- 添加一个 ContextMenuStrip 控件,然后增加“打开属性表”菜单项。
ILayer pGlobalFeatureLayer;
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
{
if (axMapControl1.LayerCount > 0)
{
esriTOCControlItem pItem = new esriTOCControlItem();
pGlobalFeatureLayer = new FeatureLayerClass();
IBasicMap pBasicMap = new MapClass();
object pOther = new object();
object pIndex = new object();
axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pBasicMap, ref pGlobalFeatureLayer, ref pOther, ref pIndex);//HitTest方法用于获取用户在TOCControl中点击的相关信息
}
if (e.button == 2)
{
contextMenuStrip1.Show(axTOCControl1, e.x, e.y);
}
}
private void 打开属性表ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 Ft = new Form2(pGlobalFeatureLayer);
Ft.Show();
}