在ArcGis Engine二次开发过程中,经常会需要用到查询统计的功能,而IQueryFilter是最常见的属性字段查询接口,可以用来做一些简单的查询工作。
现在有一些公交站点和公交路线的数据,可视化效果如下:
其中站点数据的属性信息中记录了站点名称和经过的路线,如下图所示:
功能需求为:用户输入一条公交路线,程序运行并返回这条路线经过的所有站点。
在AE程序中先建立查询的窗体,如下图所示:
这个功能需要从MapControl中获取图层,因此调用此窗体的时候需要将MapControl作为参数传入,另外还需要用到ArrayList接口,在代码中添加如下引用:
1 using System.Collections;
2 using ESRI.ArcGIS.Controls;
3 using ESRI.ArcGIS.Carto;
4 using ESRI.ArcGIS.Geodatabase;
构建一个用于属性查询的函数,返回结果为ArrayList数组,具体代码如下:
1 //查询函数
2 private ArrayList Query(AxMapControl axMapControl1, int layerIndex, string inputField, string outputField, string inputTxt)
3 {
4 IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(layerIndex) as IFeatureLayer; //获取查询的图层
5 IFeatureClass pFeatCls = pFeatureLayer.FeatureClass;
6 IQueryFilter pQueryfilter = new QueryFilterClass();
7 pQueryfilter.WhereClause = inputField + "='" + inputTxt + "'"; //设置属性查询条件
8 IFeatureCursor pFeatCur = pFeatCls.Search(pQueryfilter, false);
9 IFields pFields = pFeatCls.Fields; //获取图层的字段
10 int iField = pFields.FindField(outputField); //找出输出字段的位置
11 IFeature pFeat = pFeatCur.NextFeature();
12 ArrayList OutputList = new ArrayList(); //新建输出列表
13 while (pFeat != null)
14 {
15 OutputList.Add(pFeat.get_Value(iField).ToString());
16 pFeat = pFeatCur.NextFeature();
17 }
18 return OutputList;
19 }
在“查询”按钮的点击响应函数下添加如下代码:
1 private void button1_Click(object sender, EventArgs e)
2 {
3 string inputTxt = textBox1.Text; //获取线路值
4 if (inputTxt != null && inputTxt != "")
5 {
6 ArrayList outListBus = Query(mapControl, 1, "lineName", "name", inputTxt);
7 ArrayList outListSubway = Query(mapControl, 3, "lineName", "name", inputTxt);
8 if (outListBus.Count != 0 || outListSubway.Count != 0)
9 {
10 string outList = null;
11 if (outListBus.Count > 0) //若查询路线为公交路线
12 {
13 for (int i = 0; i < outListBus.Count - 1;i++ )
14 {
15 outList += outListBus[i].ToString() + "-->";
16 }
17 richTextBox1.Text = "经过站点:" + outList + outListBus[outListBus.Count - 1].ToString();
18 }
19 else //若查询路线为地铁路线
20 {
21 for (int i = 0; i < outListSubway.Count - 1; i++)
22 {
23 outList += outListSubway[i].ToString() + "-->";
24 }
25 richTextBox1.Text = "经过站点:" + outList + outListSubway[outListSubway.Count - 1].ToString();
26 }
27 }
28 else
29 {
30 MessageBox.Show("查无此线路,请输入正确的线路值!");
31 }
32
33 }
34 else
35 {
36 MessageBox.Show("请输入正确的线路值!");
37 }
38
39 }
最终运行结果如下:
至此,一个简单的属性查询窗体已经完成!