Ejemplo n.º 1
0
        //Query Filter
        private void btnOK_Click(object sender, EventArgs e)
        {
            m_spatialFilter.WhereClause = tbQuery.Text;

            IFeatureSelection featureSelection = (IFeatureSelection)m_layer;

            try
            {
                if (cbMethod.Text == "Create a new selection")
                {
                    featureSelection.SelectFeatures(m_spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                }
                else if (cbMethod.Text == "Add to current selection")
                {
                    featureSelection.SelectFeatures(m_spatialFilter, esriSelectionResultEnum.esriSelectionResultAdd, false);
                }
                else if (cbMethod.Text == "Remove from current selection")
                {
                    featureSelection.SelectFeatures(m_spatialFilter, esriSelectionResultEnum.esriSelectionResultSubtract, false);
                }
                else if (cbMethod.Text == "Select from current selection")
                {
                    featureSelection.SelectFeatures(m_spatialFilter, esriSelectionResultEnum.esriSelectionResultAnd, false);
                }
            }
            catch
            {
                MessageBox.Show("Invalid query!");
                this.Close();
            }

            //Show the attributes of the selected features
            ISelectionSet selectionSet = featureSelection.SelectionSet;
            ICursor       cursor;

            selectionSet.Search(null, true, out cursor); //Get the cursor
            m_FeatureCursor = cursor as IFeatureCursor;

            IFeatureLayer featureLayer = m_layer as IFeatureLayer;
            DataOperator  dataOperator = new DataOperator(m_map);

            if (selectionSet.Count > 0)
            {
                DataTable dataTable = dataOperator.GetDataTable(m_FeatureCursor, featureLayer);
                selectionSet.Search(null, true, out cursor); //Get the cursor
                m_FeatureCursor = cursor as IFeatureCursor;
                DataBoard dataBoard = new DataBoard(m_map, dataTable, m_FeatureCursor, selectionSet);
                dataBoard.SetSelectedLayer(m_layer.Name);
                dataBoard.cbEnabledFalse();
                dataBoard.Show();
            }

            m_frmMain.ActiveViewPartialRefresh();
            MessageBox.Show(selectionSet.Count + " features are selected.");
            this.Close();
        }
Ejemplo n.º 2
0
        //查找 from vec,参数为空则查找所有
        private static ArrayList queryFromRAS(string where)
        {
            ArrayList t = new ArrayList();

            IName        pName = RAS_TABLE as IName;
            ITable       table = pName.Open() as ITable;
            IQueryFilter query = new QueryFilterClass();

            query.WhereClause = where;
            ISelectionSet selectionSet = table.Select(query, esriSelectionType.esriSelectionTypeIDSet, esriSelectionOption.esriSelectionOptionNormal, null);

            ICursor cursor;

            selectionSet.Search(null, false, out cursor);
            IRow row = cursor.NextRow();

            if (selectionSet.Count > 0)
            {
                while (row != null)
                {
                    NameAndType nat = new NameAndType();
                    nat.name = row.get_Value(1) + "";
                    nat.type = "rasterDataset";
                    t.Add(nat);
                    row = cursor.NextRow();
                }
            }
            return(t);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 树节点点击事件
        /// </summary>
        private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                //首先清空DataGridView中的行和列
                dataGridView.Columns.Clear();
                dataGridView.Rows.Clear();

                //通过树节点的Tag属性获取以该节点名称命名的矢量图层
                currentFeatureLayer = e.Node.Tag as IFeatureLayer;
                //通过接口转换,使用IFeatureSelection接口获取图层的选择集
                IFeatureSelection featureSelection = currentFeatureLayer as IFeatureSelection;
                //通过ISelectionSet接口获取被选择的要素集合
                if (featureSelection == null)
                {
                    return;
                }
                ISelectionSet selectionSet = featureSelection.SelectionSet;
                //通过ISelectionSet接口的Count属性可以获取被选择要素的数量
                labelLayerSelectionCount.Text = "当前图层选择了 " + selectionSet.Count + " 个要素。";

                //对当前图层要素的属性字段进行遍历,从而建立DataGridView中的列
                //获取所有的属性字段
                IFields fields = currentFeatureLayer.FeatureClass.Fields;
                for (int i = 0; i < fields.FieldCount; i++)
                {
                    //通过遍历添加列,使用字段的AliasName作为DataGridView中显示的列名
                    dataGridView.Columns.Add(fields.get_Field(i).Name, fields.get_Field(i).AliasName);
                }

                //对选择集进行遍历,从而建立DataGridView中的行
                //定义ICursor接口的游标以遍历整个选择集
                ICursor cursor;
                //使用ISelectionSet接口的Search方法,使用null作为查询过滤器,cursor作为返回值获取整个选择集
                selectionSet.Search(null, false, out cursor);
                //进行接口转换,使用IFeatureCursor接口来获取选择集中的每个要素
                IFeatureCursor featureCursor = cursor as IFeatureCursor;
                //获取IFeature接口的游标中的第一个元素
                IFeature feature = featureCursor.NextFeature();
                //定义string类型的数组,以添加DataGridView中每一行的数据
                string[] strs;
                //当游标不为空时
                while (feature != null)
                {
                    //string数组的大小为字段的个数
                    strs = new string[fields.FieldCount];
                    //对字段进行遍历
                    for (int i = 0; i < fields.FieldCount; i++)
                    {
                        //将当前要素的每个字段值放在数组的相应位置
                        strs[i] = feature.get_Value(i).ToString();
                    }
                    //在DataGridView中添加一行的数据
                    dataGridView.Rows.Add(strs);
                    //移动游标到下一个要素
                    feature = featureCursor.NextFeature();
                }
            }
            catch { }
        }
Ejemplo n.º 4
0
        public static List <IFeature> GetFeaturesBySelected(IFeatureLayer featureLayer)
        {
            List <IFeature> list = new List <IFeature>();

            IFeatureSelection pFeatureSelection = featureLayer as IFeatureSelection;

            if (pFeatureSelection == null)
            {
                return(list);
            }
            ISelectionSet pSelectionSet = pFeatureSelection.SelectionSet;
            ICursor       pCursor       = null;

            pSelectionSet.Search(null, true, out pCursor);
            IFeatureCursor pFeatureCursor = pCursor as IFeatureCursor;

            if (pFeatureCursor == null)
            {
                return(list);
            }
            IFeature pFeature;

            while ((pFeature = pFeatureCursor.NextFeature()) != null)
            {
                list.Add(pFeature);
            }
            Marshal.ReleaseComObject(pFeatureCursor);
            Marshal.ReleaseComObject(pCursor);
            return(list);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 获取选择的要素(以cusor形式遍历)
        /// </summary>
        /// <param name="pFeatureLayer">预分析要素层</param>
        /// <returns>选择要素的游标</returns>
        public IFeatureCursor GetSelectedFeatures(IFeatureLayer pFeatureLayer)
        {
            if (pFeatureLayer == null)
            {
                //分析图层为空
                return(null);
            }
            else
            {
                IFeatureSelection pFeatSel      = null;
                ISelectionSet     pSelectionSet = null;
                ICursor           pCursor       = null;

                pFeatSel      = pFeatureLayer as IFeatureSelection;
                pSelectionSet = pFeatSel.SelectionSet;

                if (pSelectionSet.Count == 0)
                {
                    MessageBox.Show("No features are selected in the '" + pFeatureLayer.Name + "' layer");
                    return(null);
                }

                pSelectionSet.Search(null, false, out pCursor);

                //返回游标
                return(pCursor as IFeatureCursor);
            }
        }
Ejemplo n.º 6
0
        public static IGeometry GetSelectGeometry(AxMapControl axMapControl)
        {
            for (int i = 0; i < axMapControl.LayerCount; i++)
            {
                IFeatureLayer     pFeatureLayer     = axMapControl.get_Layer(i) as IFeatureLayer;
                IFeatureSelection pFeatureSelection = pFeatureLayer as IFeatureSelection;
                ISelectionSet     pSelectionSet     = pFeatureSelection.SelectionSet;

                ICursor pCursor = null;
                pSelectionSet.Search(null, false, out pCursor);
                IFeatureCursor pFeatureCursor = pCursor as IFeatureCursor;
                IFeature       pFeature       = pFeatureCursor.NextFeature();

                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                GC.Collect();
                GC.WaitForPendingFinalizers();

                if (pFeature != null)
                {
                    return(pFeature.Shape);
                }
            }

            return(null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Helper function to get a polygon object from the selected feature in the
        /// specified layer.
        /// </summary>
        /// <param name="layerName">The polygon layer that contains exactly one selected feature.</param>
        /// <returns>The polygon object, or null if none could be retrieved.</returns>
        private IPolygon4 GetPolygonFromSpecifiedLayer(ILayer layerObj)
        {
            // Set the AOI of the job, if there is one
            // Ensure that there's nothing wrong with the AOI feature that is selected, if any
            IPolygon4 aoiPolygon = null;

            if (layerObj != null)
            {
                ICursor           cursor    = null;
                IFeatureLayer     featLayer = layerObj as IFeatureLayer;
                IFeatureSelection featSel   = layerObj as IFeatureSelection;
                ISelectionSet     selSet    = featSel.SelectionSet as ISelectionSet;

                if (featLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolygon)
                {
                    throw new WmauException(new WmauError(WmauErrorCodes.C_AOI_NOT_POLYGON_ERROR));
                }
                else if (selSet.Count != 1)
                {
                    throw new WmauException(new WmauError(WmauErrorCodes.C_EXPECTED_ONE_SELECTED_FEATURE_ERROR));
                }

                // If we get this far, we know that there's exactly one selected feature, so we
                // don't have to loop through the selection set
                selSet.Search(null, true, out cursor);
                IFeatureCursor featureCursor = cursor as IFeatureCursor;
                IFeature       aoiCandidate  = featureCursor.NextFeature();

                // We also know that the feature is a polygon, so just make the cast
                aoiPolygon = aoiCandidate.Shape as IPolygon4;
            }

            return(aoiPolygon);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add CmdCreateParrallel.OnClick implementation
            IEngineEditor     pEngineEdit  = new EngineEditorClass();
            IEngineEditLayers pEEditLayers = pEngineEdit as IEngineEditLayers;
            IFeatureLayer     targetLayer  = pEEditLayers.TargetLayer;


            IFeatureSelection featureSelection = targetLayer as IFeatureSelection;
            ISelectionSet     selectionSet     = featureSelection.SelectionSet;

            if (selectionSet.Count > 0)
            {
                ICursor cursor;
                selectionSet.Search(null, true, out cursor);
                IFeatureCursor        featureCursor = cursor as IFeatureCursor;
                IFeature              feature       = null;
                FrmParallelLineOffset frm           = new FrmParallelLineOffset();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    while ((feature = featureCursor.NextFeature()) != null)
                    {
                        IPolyline pPolyline = ConstructOffset(feature.Shape as IPolyline, frm.offset);
                        IFeature  pFeature  = targetLayer.FeatureClass.CreateFeature();
                        pFeature.Shape = pPolyline;
                        pFeature.Store();
                        m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private void cbFieldNameList_SelectedIndexChanged(object sender, EventArgs e)
        {
            IFeatureClass   featureClass   = m_FeatureLayer.FeatureClass;
            IDataStatistics dataStatistics = new DataStatistics();

            //get cursor
            ICursor cursor;

            if (m_WithSelectionSet)
            {
                m_SelectionSet.Search(null, true, out cursor);
            }
            else
            {
                IFeatureCursor featureCursor = featureClass.Search(null, false);
                cursor = (ICursor)featureCursor;
            }
            dataStatistics.Cursor = cursor;

            //input field
            int index = featureClass.Fields.FindField(cbFieldNameList.SelectedItem.ToString());

            dataStatistics.Field = featureClass.Fields.get_Field(index).Name;

            //get results
            IStatisticsResults statisticsResults;

            statisticsResults = dataStatistics.Statistics;

            lbMax.Text = statisticsResults.Maximum.ToString();
            lbMin.Text = statisticsResults.Minimum.ToString();
            lbAvg.Text = statisticsResults.Mean.ToString();
        }
Ejemplo n.º 10
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            double offsetValue = -1;

            try
            {
                offsetValue = Convert.ToDouble(textEdit1.Text);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("请输入数值类型", "提示信息", MessageBoxButtons.OK);
                return;
            }
            try
            {
                //启动编辑
                IFeatureLayer featureLayer  = mLayer as IFeatureLayer;
                IFeatureClass pFeatureClass = featureLayer.FeatureClass;

                IWorkspace    workspace     = null;
                IEngineEditor mEngineEditor = mEngineEditor = new EngineEditorClass();
                if (pFeatureClass.FeatureDataset != null)
                {
                    workspace = pFeatureClass.FeatureDataset.Workspace;
                    mEngineEditor.EditSessionMode = esriEngineEditSessionMode.esriEngineEditSessionModeVersioned;
                    mEngineEditor.StartEditing(workspace, mMap);
                    ((IEngineEditLayers)mEngineEditor).SetTargetLayer(featureLayer, -1);
                    mEngineEditor.StartOperation();
                }



                ISelectionSet mSelectionSet = (mLayer as IFeatureSelection).SelectionSet;
                ICursor       mCursor;
                mSelectionSet.Search(null, false, out mCursor);

                IFeature mFeature = mCursor.NextRow() as IFeature;
                while (mFeature != null)
                {
                    IGeometry  geometry  = mFeature.ShapeCopy;
                    IPolycurve polycurve = geometry as IPolycurve;
                    polycurve.Smooth(offsetValue);
                    mFeature.Shape = polycurve as IGeometry;
                    mFeature.Store();
                    mFeature = mCursor.NextRow() as IFeature;
                }
                if (workspace != null)
                {
                    mEngineEditor.StopEditing(true);
                }

                this.Dispose();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("平滑失败", "提示信息", MessageBoxButtons.OK);
            }
        }
        /// <summary>
        /// 更新所有属性表(需要在已经初始化DataTable的情况下调用)
        /// </summary>
        private void UpdateCtrlDataSource()
        {
            if (allRowsTable == null || selectionRowsTable == null)
            {
                return;
            }
            try
            {
                if (gridAllAttribute.Visible == true)
                {
                    ICursor pCursor = null;
                    int     selectOid;
                    string where = "";
                    selectIDList = new List <int>();
                    DataColumn dataColumn = allRowsTable.Columns["选中要素"];
                    allRowsTable.Columns.Remove(dataColumn);
                    dataColumn.DefaultValue = false;
                    allRowsTable.Columns.Add(dataColumn);

                    IFeatureSelection pFeatureSelection = featureLayer as IFeatureSelection;
                    ISelectionSet     pSelectionSet     = pFeatureSelection.SelectionSet;
                    pSelectionSet.Search(null, false, out pCursor);
                    IRow pRow = pCursor.NextRow();
                    while (pRow != null)
                    {
                        selectOid = Convert.ToInt32(pRow.get_Value(pRow.Fields.FindField(oidFieldName)));
                        selectIDList.Add(selectOid);
                        pRow = pCursor.NextRow();
                    }
                    if (selectIDList.Count > 0)
                    {
                        foreach (int i in selectIDList)
                        {
                            where += oidFieldName + "=" + i + " or ";
                        }
                        where = where.Substring(0, where.Length - 3);
                        DataRow[] selectRows = allRowsTable.Select(where);
                        foreach (DataRow dataRow in selectRows)
                        {
                            dataRow["选中要素"] = true;
                        }
                    }
                    gridAllAttribute.DataSource = allRowsTable;
                    gviewAll.RefreshData();
                    ctrlGridNavigation1.InitCtrl(allRowsTable, gridAllAttribute, new int[] { 50, 100, 500 });
                }
                if (gridSelectAttribute.Visible == true)
                {
                    RefreshSelectionData();
                    gviewSelect.RefreshData();
                    ctrlGridNavigation1.InitCtrl(selectionRowsTable, gridSelectAttribute, new int[] { 50, 100, 500 });
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("属性表更新失败");
            }
        }
Ejemplo n.º 12
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            object            item             = ArcMap.Document.SelectedItem;
            IFeatureLayer     featureLayer     = item as FeatureLayer;
            IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
            ISelectionSet     selectionSet     = featureSelection.SelectionSet;
            IFeatureClass     featureClass     = featureLayer.FeatureClass;
            ICursor           cursor           = null;

            selectionSet.Search(null, true, out cursor);
            IRow row = cursor.NextRow();
            // Finding fields to save to
            int fieldStatus       = featureLayer.FeatureClass.FindField("STATUS");
            int fieldYearComplete = featureLayer.FeatureClass.FindField("YEAR_COMPLETED");
            int fieldStart        = featureLayer.FeatureClass.FindField("START_DATE");
            int fieldExp          = featureLayer.FeatureClass.FindField("EXP_DATE");
            int fieldWEA          = featureLayer.FeatureClass.FindField("RECORD_NO");
            int fieldFeature      = featureLayer.FeatureClass.FindField("FEATURE");
            int fieldCreator      = featureLayer.FeatureClass.FindField("DATAORIGIN");
            int fieldFirstName    = featureLayer.FeatureClass.FindField("FIRST_NAME");
            int fieldLastName     = featureLayer.FeatureClass.FindField("LAST_NAME");
            int fieldCounty       = featureLayer.FeatureClass.FindField("COUNTY");
            int fieldState        = featureLayer.FeatureClass.FindField("STATE");
            int fieldAcres        = featureLayer.FeatureClass.FindField("Acres");
            int fieldComments     = featureLayer.FeatureClass.FindField("COMMENTS");
            // Sets up variables to insert into save / update row
            string statusSave       = comboStatus.Text;
            string yearCompleteSave = comboYear.Text;
            string startDateSave    = dateStart.Text;
            string expDateSave      = dateExp.Text;
            string weaSave          = textWEA.Text;
            string featureSave      = textFeature.Text;
            string creatorSave      = textCreator.Text;
            string firstNameSave    = textFirstName.Text;
            string lastNameSave     = textLastName.Text;
            string countySave       = comboCounty.Text;
            string stateSave        = comboState.Text;
            string acresSave        = textAcres.Text;
            string commentsSave     = richComments.Text;

            // Update row
            row.set_Value(fieldStatus, statusSave);
            row.set_Value(fieldYearComplete, yearCompleteSave);
            row.set_Value(fieldStart, startDateSave);
            row.set_Value(fieldExp, expDateSave);
            row.set_Value(fieldFeature, featureSave);
            row.set_Value(fieldWEA, weaSave);
            row.set_Value(fieldCreator, creatorSave);
            row.set_Value(fieldFirstName, firstNameSave);
            row.set_Value(fieldLastName, lastNameSave);
            row.set_Value(fieldCounty, countySave);
            row.set_Value(fieldState, stateSave);
            row.set_Value(fieldAcres, acresSave);
            row.set_Value(fieldComments, commentsSave);

            row.Store();
            Close();
        }
Ejemplo n.º 13
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            //生成被查询的图层集以传入查询结果窗体
            lstQueryedLayer = new List <ILayer>();
            foreach (ListViewItem lvi in lstLayer.Items)
            {
                if (lvi.Checked == true)
                {
                    lstQueryedLayer.Add(lvi.Tag as ILayer);
                }
            }
            //生成选择的查询图层的搜索图形
            IFeatureLayer pFL = null;

            foreach (ILayer pLayer in lstSelectLayer)
            {
                if (pLayer.Name == cboxSearchLayer.Text)
                {
                    pFL = pLayer as IFeatureLayer;
                }
            }
            IGeometryBag gmBag = new GeometryBagClass();

            gmBag.SpatialReference = pMap.SpatialReference;//定义空间参考,否则加入的图形将失去参考
            IGeometryCollection gmCollection = gmBag as IGeometryCollection;

            if (rdSelect.Checked)//如果单选框 选择的要素是选中状态
            {
                ISelectionSet pSelSet = (pFL as IFeatureSelection).SelectionSet;
                ICursor       pCursor;
                pSelSet.Search(null, false, out pCursor);
                IFeature pFeature = (pCursor as IFeatureCursor).NextFeature();
                object   obj      = Type.Missing;
                while (pFeature != null)
                {
                    gmCollection.AddGeometry(pFeature.ShapeCopy, ref obj, ref obj);
                    pFeature = (pCursor as IFeatureCursor).NextFeature();
                }
            }
            else//如果单选框 全部要素是选择状态
            {
                IFeatureCursor pFeaCursor = pFL.FeatureClass.Search(null, false);
                IFeature       pFea       = pFeaCursor.NextFeature();
                object         obj        = Type.Missing;
                while (pFea != null)
                {
                    gmCollection.AddGeometry(pFea.ShapeCopy, ref obj, ref obj);
                    pFea = pFeaCursor.NextFeature();
                }
            }
            ISpatialIndex pSI = gmBag as ISpatialIndex;//重建索引

            pSI.AllowIndexing = true;
            pSI.Invalidate();
            GeometryBag = gmBag;
        }
        /// <summary>
        /// Create a System.DataTable from the selected features in the layer
        /// </summary>
        /// <param name="layer"></param>
        /// <remarks>
        /// Uses the properties of the layer (field names/order, selection set, definition query)
        /// and not the underlying feature class.
        /// </remarks>
        /// <returns>System.DataTable</returns>
        private DataTable MakeTableFromFeatureLayer(IGeoFeatureLayer layer)
        {
            if (layer == null)
            {
                return(null);
            }
            var           table     = new DataTable();
            ISelectionSet selection = ((IFeatureSelection)layer).SelectionSet;
            ICursor       cursor;

            if (selection.Count > 0)
            {
                selection.Search(null, true, out cursor);
            }
            else
            {
                cursor = (ICursor)layer.SearchDisplayFeatures(null, true);
            }
            //var fields2 = (ILayerFields)layer;
            //FIXME - using all fields in FC, not the fields in the display settings
            //FIXME - if I can use the layer properties, make sure I get the shape column.
            //FIXME - Caption (Alias) is not set correctly, or is not being used
            var fields = cursor.Fields;

            Type[] types = GetTypes(fields);
            for (int i = 0; i < fields.FieldCount; i++)
            {
                var column = new DataColumn
                {
                    ColumnName = fields.Field[i].Name,
                    Caption    = fields.Field[i].AliasName,
                    DataType   = types[i]
                };
                table.Columns.Add(column);
            }
            IRow row;
            int  fieldCount = cursor.Fields.FieldCount;

            while ((row = cursor.NextRow()) != null)
            {
                DataRow newRow = table.NewRow();
                for (int i = 0; i < fieldCount; i++)
                {
                    if (row.Fields.Field[i].Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        newRow[row.Fields.Field[i].Name] = GetWktFromGeometry((IGeometry)row.Value[i]);
                    }
                    else
                    {
                        newRow[row.Fields.Field[i].Name] = row.Value[i];
                    }
                }
                table.Rows.Add(newRow);
            }
            return(table);
        }
Ejemplo n.º 15
0
        private void comboLayerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboLayerList.Items.Count == 0)
            {
                return;
            }

            lstContent.Items.Clear();
            lstContent.Columns.Clear();

            ILayer        pLayer        = GetLayerByName(comboLayerList.SelectedItem.ToString());
            IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;

            if (pFeatureLayer == null)
            {
                return;
            }

            IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
            IFields       pFields       = pFeatureClass.Fields;

            for (int i = 0; i < pFields.FieldCount; i++)
            {
                lstContent.Columns.Add(pFields.get_Field(i).AliasName);
            }

            IFeatureSelection pFeatureSelection = pFeatureLayer as IFeatureSelection;
            ISelectionSet     pSelectionSet     = pFeatureSelection.SelectionSet;

            ICursor pCursor = null;

            pSelectionSet.Search(null, false, out pCursor);
            IFeatureCursor pFeatureCursor = pCursor as IFeatureCursor;

            IFeature pFeature = pFeatureCursor.NextFeature();

            while (pFeature != null)
            {
                ListViewItem item = null;
                for (int i = 0; i < pFields.FieldCount; i++)
                {
                    if (pFields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                    {
                        if (i == 0)
                        {
                            item = lstContent.Items.Add(pFeature.get_Value(i).ToString());
                        }
                        else
                        {
                            item.SubItems.Add(pFeature.get_Value(i).ToString());
                        }
                    }
                }
                pFeature = pFeatureCursor.NextFeature();
            }
        }
        private void OnActiveViewEventsAfterDraw(ESRI.ArcGIS.Display.IDisplay display, ESRI.ArcGIS.Carto.esriViewDrawPhase phase)
        {
            ESRI.ArcGIS.Carto.esriViewDrawPhase m_phase = phase;

            //if the drawing pahse geography, find all feature layer and selected feature and draw them on screen if they are polygons. Please note don't call   display::StartDrawing as it is already started by the system.
            if (m_phase == ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeography)
            {
                IMap m_Map = m_MxDoc.FocusMap;
                ESRI.ArcGIS.esriSystem.UID m_UID = new ESRI.ArcGIS.esriSystem.UID();
                m_UID.Value = "{40A9E885-5533-11d0-98BE-00805F7CED21}";
                IEnumLayer m_EnumLayer = m_Map.Layers[m_UID];
                ILayer     m_Layer     = m_EnumLayer.Next();

                //if you want to change the selection color you can change it here.
                ISimpleFillSymbol m_FillSymbol = new SimpleFillSymbol();
                m_Rgb              = new RgbColor();
                m_Rgb.Red          = 255;
                m_FillSymbol.Color = m_Rgb;
                display.SetSymbol(m_FillSymbol as ISymbol);

                do
                {
                    if (m_Layer is IFeatureLayer)
                    {
                        if (m_Layer != null)
                        {
                            IFeatureSelection m_FeatureSelection = (IFeatureSelection)m_Layer;
                            ISelectionSet     m_SelSet           = m_FeatureSelection.SelectionSet;
                            IFeatureCursor    m_FeatCur;
                            ICursor           m_Cursor;
                            m_SelSet.Search(null, false, out m_Cursor);

                            m_FeatCur = (IFeatureCursor)m_Cursor;
                            IFeature m_Feature;

                            m_Feature = m_FeatCur.NextFeature();

                            do
                            {
                                if (m_Feature != null)
                                {
                                    if (m_Feature.Shape is IPolygon)
                                    {
                                        display.DrawPolygon(m_Feature.Shape);
                                    }
                                }
                                m_Feature = m_FeatCur.NextFeature();
                            } while (m_Feature != null);
                        }
                    }
                    m_Layer = m_EnumLayer.Next();
                } while (m_Layer != null);
            }
            #endregion
        }
        /// <summary>
        /// 获取要素图层中选择要素的属性表
        /// </summary>
        /// <param name="pFeatureLayer"></param>
        /// <returns></returns>
        private DataTable GetSelectionRowsTable(IFeatureLayer pFeatureLayer)
        {
            selectIDList = new List <int>();
            DataTable pDataTable = CreateDataTableByLayer(pFeatureLayer, pFeatureLayer.Name);

            using (ComReleaser comReleaser = new ComReleaser())
            {
                string  oidFieldName = pFeatureLayer.FeatureClass.OIDFieldName;
                ICursor pCursor      = null;
                DataRow pDataRow     = null;
                comReleaser.ManageLifetime(pCursor);
                string            shapeType         = GetShapeType(pFeatureLayer);
                IFeatureSelection pFeatureSelection = featureLayer as IFeatureSelection;
                ISelectionSet     pSelectionSet     = pFeatureSelection.SelectionSet;
                if (pSelectionSet.Count == 0)
                {
                    return(pDataTable);
                }
                pSelectionSet.Search(null, false, out pCursor);
                IRow pRow = pCursor.NextRow();
                comReleaser.ManageLifetime(pRow);
                int n = 0;
                while (pRow != null)
                {
                    //新建DataTable的行对象
                    pDataRow = pDataTable.NewRow();
                    for (int i = 0; i < pRow.Fields.FieldCount; i++)
                    {
                        //如果字段类型为esriFieldTypeGeometry,则根据图层类型设置字段值
                        if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                        {
                            pDataRow["Shape"] = shapeType;
                        }
                        //当图层类型为Anotation时,要素类中会有esriFieldTypeBlob类型的数据,
                        //其存储的是标注内容,如此情况需将对应的字段值设置为Element
                        else if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeBlob)
                        {
                            pDataRow[i] = "Element";
                        }
                        else
                        {
                            string o = pRow.get_Value(i).ToString();
                            pDataRow[pRow.Fields.Field[i].Name] = pRow.get_Value(i);
                        }
                    }
                    pDataRow[0] = true;
                    selectIDList.Add(Convert.ToInt32(pDataRow[oidFieldName]));
                    pDataTable.Rows.Add(pDataRow);
                    pDataRow = null;
                    n++;
                    pRow = pCursor.NextRow();
                }
            }
            return(pDataTable);
        }
Ejemplo n.º 18
0
        private void button2_Click(object sender, EventArgs e)
        {
            GetWorkPath();
            IWorkspace        ws   = OpenShapfileWorkspace(this.strFilePath);
            IFeatureWorkspace pFWS = ws as IFeatureWorkspace;

            if (strFileName == null || strFileName != "UK_CoastlineSplit")
            {
                MessageBox.Show("Please select the CoastlineSplit in TOC");
                return;
            }
            IFeatureClass fcCoastLineSplit = pFWS.OpenFeatureClass(strFileName);
            //IQueryFilter queryFilter = new QueryFilterClass();
            ICursor cursor = (ICursor)fcCoastLineSplit.Search(null, false);
            //Get statistic of length field and get min and max values
            IDataStatistics dataStatistic = new DataStatisticsClass();
            int             fieldindex    = fcCoastLineSplit.Fields.FindField("length");

            if (fieldindex == -1)
            {
                MessageBox.Show("Please add 'length' field!");
                return;
            }
            dataStatistic.Field  = "length";
            dataStatistic.Cursor = cursor;
            ESRI.ArcGIS.esriSystem.IStatisticsResults staResult = dataStatistic.Statistics;
            // round the result in 4 decimals
            maxLength     = Math.Round(staResult.Maximum, 4).ToString();
            minLength     = Math.Round(staResult.Minimum, 4).ToString();
            meanLength    = Math.Round(staResult.Mean, 4).ToString();
            textBox2.Text = minLength;
            textBox3.Text = maxLength;
            textBox4.Text = meanLength;
            // If minimum length is smaller than 1 meter, set the minimum to the minimum value greater than 1 meter
            if (staResult.Minimum <= 1)
            {
                if (MessageBox.Show("The minimum length is shorter than 1 meter, change the minimum value greater than 1?", "Note", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = "length > 1";
                    ISelectionSet  pSelectionSet = fcCoastLineSplit.Select(queryFilter, esriSelectionType.esriSelectionTypeHybrid, esriSelectionOption.esriSelectionOptionNormal, null);
                    IFeatureCursor pFCursor;
                    ICursor        pCursor;
                    pSelectionSet.Search(null, true, out pCursor);
                    pFCursor             = pCursor as IFeatureCursor;
                    dataStatistic        = new DataStatisticsClass();
                    dataStatistic.Field  = "length";
                    dataStatistic.Cursor = pCursor;
                    staResult            = dataStatistic.Statistics;
                    minLength            = Math.Round(staResult.Minimum, 4).ToString();
                    textBox2.Text        = minLength;
                }
            }
        }
Ejemplo n.º 19
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (Button == 1)
            {
                setalllayerSelectable();
                IFeatureLayer featurelayer = eep.TargetLayer as IFeatureLayer;
                if (featurelayer == null)
                {
                    MessageBox.Show("请启动编辑!并选择目标图层!"); return;
                }
                IPoint pt = activeview.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                ITopologicalOperator topo = pt as ITopologicalOperator;
                IGeometry            pGeo = topo.Buffer(5);
                pt.SpatialReference = map.SpatialReference;
                ISpatialFilter sf = new SpatialFilterClass();
                sf.Geometry      = pGeo;
                sf.GeometryField = featurelayer.FeatureClass.ShapeFieldName;
                switch (featurelayer.FeatureClass.ShapeType)
                {
                case esriGeometryType.esriGeometryPoint: sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; break;

                case esriGeometryType.esriGeometryPolyline: sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; break;

                case esriGeometryType.esriGeometryPolygon: sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; break;
                }

                IFeatureSelection pfs = featurelayer as IFeatureSelection;
                pfs.SelectFeatures(sf, esriSelectionResultEnum.esriSelectionResultNew, true);
                ISelectionSet ss = pfs.SelectionSet;
                ICursor       pcursor;
                ss.Search(null, true, out pcursor);
                IFeatureCursor pfcursor = pcursor as IFeatureCursor;
                IFeature       pfeature = pfcursor.NextFeature();
                if (pfeature != null)
                {
                    activeview.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeview.Extent);
                    DialogResult result;
                    result = MessageBox.Show("确定删除该要素?", "Question Dialog", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    if (DialogResult.Yes == result)
                    {
                        pfeature.Delete(); activeview.Refresh();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("未选中要素"); return;
                }
            }
        }
Ejemplo n.º 20
0
        public override void OnClick()
        {
            if (_AppHk == null)
            {
                return;
            }
            if (_AppHk.MapControl == null)
            {
                return;
            }

            IFeatureLayer tmpFeatureLayer = getEditLayer.isExistLayer(_AppHk.MapControl.Map) as IFeatureLayer;

            if (tmpFeatureLayer == null || tmpFeatureLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint)
            {
                MessageBox.Show("请设置编辑图层为点图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            IWorkspaceEdit iWE = (tmpFeatureLayer.FeatureClass as IDataset).Workspace as IWorkspaceEdit;

            if (!iWE.IsBeingEdited())
            {
                iWE.StartEditing(false);
            }
            ISelectionSet iSS = (tmpFeatureLayer as IFeatureSelection).SelectionSet;
            ICursor       iCursor;

            iSS.Search(null, false, out iCursor);
            IFeatureCursor iFC        = iCursor as IFeatureCursor;
            IFeature       tmpFeature = iFC.NextFeature();

            if (tmpFeature == null)
            {
                return;
            }
            if (tmpFeature.ShapeCopy.GeometryType != esriGeometryType.esriGeometryPoint)
            {
                MessageBox.Show("请选择点要素!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (MessageBox.Show("是否删除选择的点!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
            {
                return;
            }
            while (tmpFeature != null)
            {
                tmpFeature.Delete();
                tmpFeature = iFC.NextFeature();
            }
            iWE.StopEditing(true);
            iWE = null;
            _AppHk.MapControl.ActiveView.Refresh();
        }
Ejemplo n.º 21
0
        private void InitTreeView(ISelectionSet pSelectSet, ILayer pLayer)
        {
            if (pSelectSet == null || pLayer == null)
            {
                return;
            }

            IFeatureClass pFtCls = ((IFeatureLayer)pLayer).FeatureClass;

            if (pFtCls == null)
            {
                return;
            }
            IFields pFields = pFtCls.Fields;

            //这里如果数据没有bsm怎么办
            int nIndex = pFields.FindField("BSM");

            if (nIndex == -1)
            {
                return;
            }


            string strId;

            ICursor pCursor;

            pSelectSet.Search(null, false, out pCursor);
            IRow pRow = pCursor.NextRow();

            if (pRow == null)
            {
                return;
            }

            TreeListNode noderoot =
                this.FTtreeList.AppendNode(new object[] { pLayer.Name }, null);

            while (pRow != null)
            {
                //strId = pRow.OID.ToString();
                if (pRow.get_Value(nIndex) != null)
                {
                    strId = pRow.get_Value(nIndex).ToString();
                    //NodeRoot.Nodes.Add(strId);
                    TreeListNode node =
                        this.FTtreeList.AppendNode(new object[] { strId }, noderoot);
                }

                pRow = pCursor.NextRow();
            }
        }
Ejemplo n.º 22
0
        public void AddQueryResult(TreeNode pNode, IFeatureLayer pFeatLyr, ISelectionSet pSelectionSet)
        {
            try
            {
                if (pSelectionSet == null)
                {
                    return;
                }
                if (pSelectionSet.Count == 0)
                {
                    return;
                }
                if (pFeatLyr == null)
                {
                    return;
                }
                TreeNode      curNode  = null;
                IFeatureClass pFeatCls = null;
                IDataset      pDataSet = null;
                int           i        = 0;

                pFeatCls = pFeatLyr.FeatureClass;
                pDataSet = (IDataset)pFeatCls;
                curNode  = pNode.Nodes.Add(pFeatLyr.Name);

                curNode.Tag = "地物层";
                curNode.Expand();

                IFeature       pFeat   = null;
                TreeNode       xNode   = null;
                ICursor        pCursor = null;
                IFeatureCursor pFeatCur;
                pSelectionSet.Search(null, false, out pCursor);

                pFeatCur = (IFeatureCursor)pCursor;
                pFeat    = pFeatCur.NextFeature();
                while (pFeat != null)
                {
                    i         = i + 1;
                    xNode     = curNode.Nodes.Add(GetKey(pFeat, i), GetString(pFeat));
                    xNode.Tag = pFeat;
                    m_FeaturesInTree.Add(pFeat, GetKey(pFeat, i), null, null);
                    pFeat = pFeatCur.NextFeature();
                }
                tvwFeatures.ExpandAll();
            }
            catch (Exception)
            {
                //ClsDeclare.g_ErrorHandler.DisplayInformation("加载树图出错,请检查。错误信息:"+ex.Message, false,null,null);
                throw;
            }
        }
Ejemplo n.º 23
0
        public override void OnClick()
        {
            if (_AppHk == null)
            {
                return;
            }
            if (_AppHk.MapControl == null)
            {
                return;
            }
            IFeatureLayer tmpFeatureLayer = getEditLayer.isExistLayer(_AppHk.MapControl.Map) as IFeatureLayer;

            if (tmpFeatureLayer == null)
            {
                MessageBox.Show("请设置编辑图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            IWorkspaceEdit iWE = (tmpFeatureLayer.FeatureClass as IDataset).Workspace as IWorkspaceEdit;

            if (!iWE.IsBeingEdited())
            {
                iWE.StartEditing(false);
            }
            ISelectionSet iSS = (tmpFeatureLayer as IFeatureSelection).SelectionSet;
            ICursor       iCursor;

            iSS.Search(null, false, out iCursor);
            IFeatureCursor iFC        = iCursor as IFeatureCursor;
            IFeature       tmpFeature = iFC.NextFeature();

            if (tmpFeature == null)
            {
                MessageBox.Show("请选择编辑图层上要删除的图元!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show("是否删除选择的图元!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
            {
                return;
            }
            iWE.StartEditOperation();
            while (tmpFeature != null)
            {
                tmpFeature.Delete();
                tmpFeature = iFC.NextFeature();
            }
            iWE.StopEditOperation();
            Plugin.LogTable.Writelog(Caption);
            //iWE.StopEditing(true);
            iWE = null;
            _AppHk.MapControl.ActiveView.Refresh();
        }
Ejemplo n.º 24
0
        public void OnFinishSketch()
        {
            //get reference to featurelayer being edited
            IFeatureLayer featureLayer = m_editLayer.TargetLayer as IFeatureLayer;
            //get reference to the sketch geometry
            IGeometry reshapeGeom = m_editSketch.Geometry;

            if (reshapeGeom.IsEmpty == false)
            {
                //get the currently selected feature
                IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
                ISelectionSet     selectionSet     = featureSelection.SelectionSet;
                ICursor           cursor;
                selectionSet.Search(null, false, out cursor);
                IFeatureCursor featureCursor = cursor as IFeatureCursor;
                //the PerformSketchToolEnabledChecks property has already checked that only 1 feature is selected
                IFeature feature = featureCursor.NextFeature();

                //Take a copy of geometry for the selected feature
                IGeometry editShape = feature.ShapeCopy;

                //create a path from the editsketch geometry
                IPointCollection reshapePath = new PathClass();
                reshapePath.AddPointCollection(reshapeGeom as IPointCollection);

                //reshape the selected feature
                IPolyline polyline = editShape as IPolyline;
                polyline.Reshape(reshapePath as IPath);

                #region Perform an edit operation to store the new geometry for selected feature

                try
                {
                    m_engineEditor.StartOperation();
                    feature.Shape = editShape;
                    feature.Store();
                    m_engineEditor.StopOperation("Reshape Feature");
                }
                catch (Exception ex)
                {
                    m_engineEditor.AbortOperation();
                    System.Diagnostics.Trace.WriteLine(ex.Message, "Reshape Geometry Failed");
                }

                #endregion
            }

            //refresh the display
            IActiveView activeView = m_engineEditor.Map as IActiveView;
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, (object)featureLayer, activeView.Extent);
        }
Ejemplo n.º 25
0
        public bool QueryIntersect(string srcLayerName, string tgtLayerName,
                                   IMap iMap, esriSpatialRelationEnum spatialRel)
        {
            DataOperator dataOperator = new DataOperator(iMap);

            //Get layer by name
            IFeatureLayer iSrcLayer = (IFeatureLayer)dataOperator.GetLayerByName(srcLayerName);
            IFeatureLayer iTgtLayer = (IFeatureLayer)dataOperator.GetLayerByName(tgtLayerName);

            //using query filter to get geom
            IGeometry      geom;
            IFeature       feature;
            IFeatureCursor featCursor;
            IFeatureClass  srcFeatClass;
            IQueryFilter   queryFilter = new QueryFilter();

            queryFilter.WhereClause = "CONTINENT='Asia'"; //set query clause
            featCursor = iTgtLayer.FeatureClass.Search(queryFilter, false);
            feature    = featCursor.NextFeature();
            geom       = feature.Shape;

            //city attributes filter
            srcFeatClass = iSrcLayer.FeatureClass;
            ISpatialFilter spatialFilter = new SpatialFilter();

            spatialFilter.Geometry    = geom;
            spatialFilter.WhereClause = "POP_RANK>5";
            spatialFilter.SpatialRel  = (ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum)spatialRel;

            //select features
            IFeatureSelection featureSelection = (IFeatureSelection)iSrcLayer;

            featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

            ISelectionSet selectionSet = featureSelection.SelectionSet;
            ICursor       cursor;

            selectionSet.Search(null, true, out cursor);
            IFeatureCursor featureCursor = cursor as IFeatureCursor;

            if (selectionSet.Count > 0)
            {
                DataBoard dataBoard = new DataBoard(iMap, dataOperator.GetDataTable(featureCursor, iSrcLayer));
                dataBoard.cbEnabledFalse();
                dataBoard.Show();
            }


            return(true);
        }
Ejemplo n.º 26
0
        private void moveFeature(int x, int y)
        {
            IFeatureLayer  curLayer = getEditLayer.isExistLayer(m_MapControl.Map) as IFeatureLayer;
            IWorkspaceEdit iWE      = (curLayer.FeatureClass as IDataset).Workspace as IWorkspaceEdit;

            if (!iWE.IsBeingEdited())
            {
                iWE.StartEditing(false);
            }

            IFeatureSelection curLayerSn = curLayer as IFeatureSelection;
            ISelectionSet     pSS        = curLayerSn.SelectionSet;

            if (pSS.Count != 1)
            {
                return;
            }
            ISelectionSet iSS = (curLayer as IFeatureSelection).SelectionSet;
            ICursor       iCursor;

            iSS.Search(null, false, out iCursor);
            IFeatureCursor iFC        = iCursor as IFeatureCursor;
            IFeature       tmpFeature = iFC.NextFeature();
            IPoint         pPnt       = m_MapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
            IGeometry      pGeometry  = tmpFeature.ShapeCopy;

            if (pGeometry.GeometryType == esriGeometryType.esriGeometryPoint)
            {
                pGeometry = pPnt;
            }
            else if (pGeometry.GeometryType == esriGeometryType.esriGeometryPolyline || pGeometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                double offX = 0, offY = 0;
                offX = pGeometry.Envelope.XMin + pGeometry.Envelope.Width / 2 - pPnt.X;
                offY = pGeometry.Envelope.YMin + pGeometry.Envelope.Height / 2 - pPnt.Y;
                ITransform2D iT2D = pGeometry as ITransform2D;
                iT2D.Move(-offX, -offY);
            }
            iWE.StartEditOperation();
            tmpFeature.Shape = pGeometry;
            tmpFeature.Store();
            iWE.StopEditOperation();
            //iWE.StopEditing(true);
            iWE = null;
            curLayerSn.Clear();
            curLayerSn.Add(tmpFeature);
            m_MapControl.ActiveView.Refresh();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 获得图层选中的要素集
        /// </summary>
        /// <params name="geometry"></params>
        /// <params name="featureLayer"></params>
        /// <returns>要素OID组成的字符串</returns>
        private string GetLayerFeatureSelectSet(IGeometry geometry, IFeatureLayer featureLayer)
        {
            try
            {
                //空间滤过器
                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry   = geometry;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;//设置空间滤过关系
                //获得选中要素
                IFeatureSelection pFSelection = featureLayer as IFeatureSelection;
                pFSelection.SelectFeatures(pSpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                ISelectionSet pSelectionset = pFSelection.SelectionSet;
                ICursor       pCursor;
                pSelectionset.Search(null, true, out pCursor);
                IFeatureCursor pFeatCursor      = pCursor as IFeatureCursor;
                IFeature       pFeature         = pFeatCursor.NextFeature();
                List <string>  lstFeatureIDs    = new List <string>();
                string         sLayerFeatureIDS = "";
                while (pFeature != null)
                {
                    string sFeatureID = pFeature.OID.ToString();//应用要素的OID字段
                    if (!lstFeatureIDs.Contains(sFeatureID))
                    {
                        lstFeatureIDs.Add(sFeatureID);
                        sLayerFeatureIDS = sLayerFeatureIDS + sFeatureID + ",";
                    }

                    pFeature = pFeatCursor.NextFeature();
                }

                sLayerFeatureIDS = sLayerFeatureIDS.TrimEnd(",".ToCharArray());

                if (pCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor);
                }
                if (pFeatCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatCursor);
                }

                return(sLayerFeatureIDS);
            }
            catch
            {
                return("");
            }
        }
Ejemplo n.º 28
0
        public EnumCursor([NotNull] ISelectionSet selectionSet,
                          [CanBeNull] IQueryFilter queryFilter,
                          bool recycle) : this(selectionSet.Target, queryFilter)
        {
            Assert.ArgumentNotNull(selectionSet, nameof(selectionSet));

            try
            {
                selectionSet.Search(queryFilter, recycle, out _cursor);
            }
            catch (Exception e)
            {
                throw new DataException(
                          CreateMessage(_table, _subFields, _whereClause, _isSpatialFilter), e);
            }
        }
Ejemplo n.º 29
0
        private static bool MouseOnSelection(IFeatureLayer pFeatureLay, IPoint pPnt, IActiveView pActiveView, double Length)
        {
            IFeatureSelection pFeatureSelection = pFeatureLay as IFeatureSelection;

            if (pFeatureSelection == null)
            {
                return(false);
            }
            ISelectionSet pSelectionSet = pFeatureSelection.SelectionSet;

            if (pSelectionSet.Count == 0)
            {
                return(false);
            }
            ICursor pCursor = null;

            pSelectionSet.Search(null, false, out pCursor);
            IFeatureCursor pFeatureCursor = pCursor as IFeatureCursor;

            if (pFeatureCursor == null)
            {
                return(false);
            }
            IFeature pFeature = pFeatureCursor.NextFeature();

            while (pFeature != null)
            {
                IGeometry4 pGeom = pFeature.ShapeCopy as IGeometry4;
                //给pGeom一个确定的空间参考
                pGeom.Project(pActiveView.FocusMap.SpatialReference);
                if (pGeom.IsEmpty)
                {
                    continue;
                }

                IProximityOperator pObj    = pGeom as IProximityOperator;
                double             dblDist = pObj.ReturnDistance(pPnt);
                if (dblDist < Length)
                {
                    return(true);
                }

                pFeature = pFeatureCursor.NextFeature();
            }

            return(false);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 得到指定图层上的选中的features
        /// </summary>
        /// <param name="map">地图</param>
        /// <param name="layerName">图层名</param>
        /// <returns>包含选中要素的IFeatureCursor</returns>
        public static IFeatureCursor getSelectFeatures(IMap map, string layerName)
        {
            IFeatureLayer featureLayer = getFeatureLayerByName(map, layerName);
            //得到选中的feature
            IFeatureClass     inputFeatureClass = featureLayer.FeatureClass;
            IDataset          inputDataset      = (IDataset)inputFeatureClass;
            IDatasetName      inputDatasetName  = (IDatasetName)inputDataset.FullName;
            IFeatureSelection featureSelection  = (IFeatureSelection)featureLayer;
            ISelectionSet     selectionSet      = featureSelection.SelectionSet;

            ICursor cursor;

            selectionSet.Search(null, false, out cursor);
            IFeatureCursor featureCursor = (IFeatureCursor)cursor;

            return(featureCursor);
        }
        /// <summary>
        /// Excecute is called by Data Reviewer engine and passed the appropriate parameters.
        /// </summary>
        /// <param name="ipSelectionToValidate">ISelectionSet of features/rows to validate</param>
        /// <param name="arguments">comma delimited string of arguments</param>
        /// <returns>
        /// Collection of validation results.
        /// </returns>
        public IPLTSErrorCollection Execute(ISelectionSet ipSelectionToValidate, string arguments)
        {
            if (null == ipSelectionToValidate)
            {
                throw new ArgumentNullException("ISelectionSet parameter is null");
            }

            if (String.IsNullOrEmpty(arguments))
            {
                throw new ArgumentNullException("string parameter is null or empty");
            }
            
            //Exit if there is nothing to check
            if (0 == ipSelectionToValidate.Count)
            {
                return new PLTSErrorCollectionClass();
            }

            //Arguments and default values
            string strTargetFeatureClassName = "";
            string strTargetSubtypeNumber = "";
            string strSourceWhereClause = "";
            string strTargetWhereClause = "";
            esriSpatialRelEnum eSpatialOperation = esriSpatialRelEnum.esriSpatialRelIntersects;
            string strSpatialRelDescription = "";
            string strUserMessage = "";

            //Split comma delimited string into array
            string[] arrayOfArguments = arguments.Split(new char[] { ',' }, StringSplitOptions.None);

            //Parse arguments
            for (int i = 0; i < arrayOfArguments.Length; i++)
            {
                if (0 == i)
                {
                    strTargetFeatureClassName = arrayOfArguments[i];
                }
                else if (1 == i)
                {
                    strTargetSubtypeNumber = arrayOfArguments[i];
                }
                else if (2 == i)
                {
                    try
                    {
                        eSpatialOperation = (esriSpatialRelEnum)Convert.ToInt32(arrayOfArguments[i]);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(String.Format("Error converting spatial operation parameter to esriSpatialRelEnum. Parameter value {0}", arrayOfArguments[i]), ex);
                    }
                }
                else if (3 == i)
                {
                    strTargetWhereClause = arrayOfArguments[i];
                }
                else if (4 == i)
                {
                    strSourceWhereClause = arrayOfArguments[i];
                }
                else if (5 == i)
                {
                    strSpatialRelDescription = arrayOfArguments[i];
                }
                else if (6 == i)
                {
                    strUserMessage = arrayOfArguments[i];
                }
                else
                {
                    throw new Exception("Invalid number of arguments. Only seven arguments are allowed. Arguments: (" + arguments + ")");
                }
            }

            //Get handle to workspace
            IDataset ipSourceDataset = ipSelectionToValidate.Target as IDataset;
            IFeatureWorkspace ipFeatureWorkspace = ipSourceDataset.Workspace as IFeatureWorkspace;

            //Open the target feature class. Feature class name passed in should be fully qualified.
            IFeatureClass ipTargetFeatureClass = ipFeatureWorkspace.OpenFeatureClass(strTargetFeatureClassName);
            if (null == ipTargetFeatureClass)
            {
                throw new Exception(String.Format("Unable to open feature class {0} from workspace {1}", strTargetFeatureClassName, (ipFeatureWorkspace as IWorkspace).PathName));
            }

            string strTargetSubtypeFieldName = (ipTargetFeatureClass as ISubtypes).SubtypeFieldName;

            //Setup spatial filter to apply to target feature class
            ISpatialFilter ipTargetSF = new SpatialFilterClass();
            ipTargetSF.SpatialRel = eSpatialOperation;

            if ("*" == strTargetSubtypeNumber || String.IsNullOrEmpty(strTargetSubtypeNumber))
            {
                if (strTargetWhereClause.Length > 0)
                {
                    ipTargetSF.WhereClause = strTargetWhereClause;
                }

            }
            else
            {
                if (strTargetWhereClause.Length > 0)
                {
                    ipTargetSF.WhereClause = strTargetSubtypeFieldName + " = " + strTargetSubtypeNumber + " AND " + strTargetWhereClause;
                }
                else
                {
                    ipTargetSF.WhereClause = strTargetSubtypeFieldName + " = " + strTargetSubtypeNumber;
                }
            }

            if (eSpatialOperation == esriSpatialRelEnum.esriSpatialRelRelation)
            {
                ipTargetSF.SpatialRelDescription = strSpatialRelDescription;
            }

            //Prepare source where clause
            IQueryFilter ipSourceQF = new QueryFilterClass();

            if (strSourceWhereClause.Length > 0)
            {
                ipSourceQF.WhereClause = strSourceWhereClause;
            }

            IPLTSErrorCollection ipRevResultCollection = new PLTSErrorCollectionClass();
            
            //Loop through source geometries and perform a spatial query againts the target Feature Class.
            //For each geometry that does not satisfy the spatial relationship add a Reviewer result.
            ICursor ipCursor = null;
            ipSelectionToValidate.Search(ipSourceQF, false, out ipCursor);

            IFeatureCursor ipFeatureCursor = ipCursor as IFeatureCursor;
            IFeature  ipSourceFeature = ipFeatureCursor.NextFeature();

            while (null != ipSourceFeature)
            {
                Application.DoEvents();
                    
                IGeometry ipSourceGeometry = ipSourceFeature.ShapeCopy;
                ipTargetSF.Geometry = ipSourceGeometry;

                //If spatial filter returns zero records create a Reviewer result.
                if (ipTargetFeatureClass.FeatureCount(ipTargetSF) == 0)
                {
                    //Create a Reviewer result
                    IPLTSError2 ipReviewerResult = new PLTSErrorClass() as IPLTSError2;
                    ipReviewerResult.ErrorKind = pltsValErrorKind.pltsValErrorKindStandard;
                    ipReviewerResult.OID = ipSourceFeature.OID;
                    ipReviewerResult.LongDescription = strUserMessage;
                    ipReviewerResult.QualifiedTableName = ipSourceDataset.Name;
                    ipReviewerResult.ErrorGeometry = ipSourceGeometry;
                    ipRevResultCollection.AddError(ipReviewerResult);
                }

                ipSourceFeature = ipFeatureCursor.NextFeature();
            }//end while loop

            //Release cursor
            Marshal.ReleaseComObject(ipFeatureCursor);
            ipFeatureCursor = null;
            Marshal.ReleaseComObject(ipCursor);
            ipCursor = null;

            //Return the collection of results
            return ipRevResultCollection;
        }
Ejemplo n.º 32
0
        private void assignMapUnit(ISelectionSet theSelection, IFeatureLayer mapUnitPolysLayer, DescriptionOfMapUnitsAccess.DescriptionOfMapUnit dmuEntry)
        {
            // Pass the selected features into a cursor that we can iterate through
            ICursor theCursor;
            theSelection.Search(null, false, out theCursor);
            string mupIdField = mapUnitPolysLayer.DisplayField;
            int IdFld = theCursor.FindField(mupIdField);

            // Build the Where Clause to get these features by looping through the cursor
            string sqlWhereClause = mupIdField + " = '";
            IRow theRow = theCursor.NextRow();
            while (theRow != null)
            {
                sqlWhereClause += theRow.get_Value(IdFld) + "' OR " + mupIdField + " = '";
                theRow = theCursor.NextRow();
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(theCursor);

            // If we didn't add anything to the where clause, bail
            if (sqlWhereClause == mupIdField + " = '") { return; }

            // Cleanup the where clause
            sqlWhereClause = sqlWhereClause.Remove(sqlWhereClause.Length - (" OR " + mupIdField + " = '").Length);

            // Get the MapUnitPolys
            MapUnitPolysAccess polysAccess = new MapUnitPolysAccess(m_theWorkspace, mapUnitPolysLayer.Name);
            polysAccess.AddMapUnitPolys(sqlWhereClause);

            //---------------------------------------------------------------------------------
            //---------------------------------------------------------------------------------
            // Data Access Issue: I actually have to pass the dictionary into another object.
            //  If I don't, once the first record is updated, the dictionary is changed.
            //  Then the foreach loop fails, because what it is looping through was adjusted.
            //  Not very happy with this.
            //---------------------------------------------------------------------------------
            //---------------------------------------------------------------------------------

            // Sort using Linq syntax
            var sortedPolys = (
                from entry in polysAccess.MapUnitPolysDictionary
                select entry);

            MapUnitPolysAccess secondPolysAccess = new MapUnitPolysAccess(m_theWorkspace, mapUnitPolysLayer.Name);
            try
            {
                // Cycle through the MapUnitPolys and update the MapUnit and Label  attributes
                foreach (KeyValuePair<string, MapUnitPolysAccess.MapUnitPoly> anEntry in sortedPolys)
                {
                    // Get the MapUnitPoly object
                    secondPolysAccess.AddMapUnitPolys(mupIdField + " = '" + anEntry.Value.MapUnitPolys_ID + "'");
                    MapUnitPolysAccess.MapUnitPoly aPoly = secondPolysAccess.MapUnitPolysDictionary[anEntry.Value.MapUnitPolys_ID];

                    // Change the appropriate values
                    aPoly.MapUnit = dmuEntry.MapUnit;
                    aPoly.Label = dmuEntry.Label;

                    // Update the Poly
                    secondPolysAccess.UpdateMapUnitPoly(aPoly);
                }
            }
            catch (Exception err) { MessageBox.Show(err.Message); }

            // Save updates
            secondPolysAccess.SaveMapUnitPolys();

            // Update the active view
            ArcMap.Document.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, mapUnitPolysLayer, null);
        }
        /// <summary>
        /// Excecute is called by Data Reviewer engine and passed the appropriate parameters.
        /// </summary>
        /// <param name="ipSelectionToValidate">ISelectionSet of features/rows to validate</param>
        /// <param name="arguments">comma delimited string of arguments</param>
        /// <returns>
        /// Collection of validation results.
        /// </returns>
        public IPLTSErrorCollection Execute(ISelectionSet ipSelectionToValidate, string arguments)
        {
            if (null == ipSelectionToValidate)
            {
                throw new ArgumentNullException("ISelectionSet parameter is null");
            }

            if (String.IsNullOrEmpty(arguments))
            {
                throw new ArgumentNullException("string parameter is null or empty");
            }

            //Get cursor of selected features/rows
            ICursor ipCursor = null;
            ipSelectionToValidate.Search(null, true, out ipCursor);

            IDataset ipSourceDataset = ipSelectionToValidate.Target as IDataset;
            IFeatureClass ipSourceFeatureClass = null;
            
            //Setup reference to feature class to be used when creating results
            if (ipSourceDataset.Type == esriDatasetType.esriDTFeatureClass)
            {
                ipSourceFeatureClass = ipSourceDataset as IFeatureClass;
            }

            //Get the index of the field we are checking
            int iIndexOfField = -1;
            iIndexOfField = ipCursor.FindField(arguments); //arguments is the name of the field we are checking

            if (-1 == iIndexOfField)
            {
                throw new Exception(String.Format("Field {0} was not found in Dataset {1}", arguments, ipSourceDataset.Name));
            }

            //Collection of results passed back to Data Reviewer
            IPLTSErrorCollection ipRevResultCollection = new PLTSErrorCollectionClass();

            //Loop through rows and check if field is numeric
            IRow ipRow = ipCursor.NextRow();
            while (null != ipRow)
            {
                object oValue = ipRow.get_Value(iIndexOfField);
                bool bIsNumeric = false;
                if (null != oValue)
                {
                    double dOutValue;
                    bIsNumeric = double.TryParse(oValue.ToString().Trim(),
                        System.Globalization.NumberStyles.Any,
                        System.Globalization.CultureInfo.CurrentCulture,
                        out dOutValue);
                }

                if (!bIsNumeric)
                {
                    //Create Reviewer result and add to collection
                    IPLTSError2 ipRevResult = new PLTSErrorClass() as IPLTSError2;
                    ipRevResult.ErrorKind = pltsValErrorKind.pltsValErrorKindStandard;
                    ipRevResult.OID = ipRow.OID;
                    ipRevResult.QualifiedTableName = ipSourceDataset.Name;
                    ipRevResult.ShortDescription = "Field does not contain a number";
                    ipRevResult.LongDescription = oValue.ToString() + " in " + arguments + " is not a number.";

                    if (null != ipSourceFeatureClass)
                    {
                        IFeature ipFeature = ipSourceFeatureClass.GetFeature(ipRow.OID);
                        if (null != ipFeature)
                        {
                            ipRevResult.ErrorGeometry = ipFeature.ShapeCopy;
                        }
                    }

                    ipRevResultCollection.AddError(ipRevResult);
                }
                
                ipRow = ipCursor.NextRow();
            }//end while

            //Release cursor
            Marshal.ReleaseComObject(ipCursor);
            ipCursor = null;

            //Return the collection of results
            return ipRevResultCollection;
        }
Ejemplo n.º 34
0
        private void InitTreeView( ISelectionSet pSelectSet,ILayer pLayer )
        {
            if( pSelectSet==null || pLayer==null )
                return;

            IFeatureClass pFtCls = ((IFeatureLayer)pLayer).FeatureClass;

            if (pFtCls == null)
                return;
            IFields pFields = pFtCls.Fields;

            //这里如果数据没有bsm怎么办
            int nIndex = pFields.FindField("BSM");
            if (nIndex == -1)
            {
                return;

            }

            string strId;

            ICursor pCursor;

            pSelectSet.Search( null,false,out pCursor );
            IRow pRow = pCursor.NextRow();
            if (pRow == null)
            {
                return;
            }

            TreeListNode noderoot =
               this.FTtreeList.AppendNode(new object[] { pLayer.Name }, null);

            while( pRow != null )
            {
                //strId = pRow.OID.ToString();
                if (pRow.get_Value(nIndex) != null)
                {
                    strId = pRow.get_Value(nIndex).ToString();
                    //NodeRoot.Nodes.Add(strId);
                    TreeListNode node =
               this.FTtreeList.AppendNode(new object[] { strId }, noderoot);

                }

                pRow = pCursor.NextRow();
            }
        }