Introduction to Programming with DotSpatialShape File, Attribute Table Operations and Printing map in DotSpatial Tutorial (4) Purpose of this tutorial: Become familiar with the following operations in DotSpatial: 1. Shape file related operations. 1.1) Creating the following types of shape files: Point, Polyline, Polygon 1.2) Add an attribute to the above shape files. 1.3) Save the shape files with user defined attributes. 2. Attribute table related operations. 2.1) View an attribute table of a shape file. 2.2) Add a new column into an attribute table. 2.3) Remove a column from an attribute table. 2.4) Update an attribute column in the shapefile. 2.3) Export an attribute to table to MS Excel worksheet. 3. Printing a map in DotSpatial. 3.1) Implement a print operation. 3.2) Set a print document properties. (North Arrow, Legend, Scale bar, Title) This tutorial has 5 important steps. Step 1: Download the DotSpatial class library Step 2: Add the DotSpatial reference and change the compile option. Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox. Step 4: Design the GUI. (GUI - Graphical User Interface) Step 5: Write the code for implementing the map operations. Teva ~ Veluppillai Page 1 Introduction to Programming with DotSpatial Step 1: Download the DotSpatial class library This step is as same as the Tutorial #1 step 1. Step 2: Add the DotSpatial reference and change the compile option. 2.1) Add the required DotSpatial reference in the visual studio development environment. Create a new VB or C# application and right click over the project on the solution explorer. On the context menu select the add reference and add the following reference from the DotSpatial folder. DotSpatial.Data.Forms.dll, DotSpatial.Symbology.dll, DotSpatial.Controls.dll, DotSpatial.Projections.dll, DotSpatial.Data.dll, DotSpatial.Topology.dll Fig. 1 Required references. Teva ~ Veluppillai Page 2 Introduction to Programming with DotSpatial Fig. 2 Required references on Visual Studio Development Environment. 2.2) Change the compile option from .Net FrameWork 4 Client Profile to .Net FrameWork 4 This step is as same as the Tutorial # 1 step 2.2. Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox. This step is as same as the Tutorial # 1 step 3. Step 4: Design the GUI. (Graphical User Interface) Design the GUI as follows: Teva ~ Veluppillai Page 3 2) Sub menu items: Under File menu item create 3 sub menu items as follows: Load.3. and Attribute Table Operations 2. 2. Under the Shapefile Operations create the following sub menu items : Point . Add four panel controls. Final GUI Interface design considerations. Menu should be contains the following menu items. Shapefile Operations.1) Main menu item: File.Introduction to Programming with DotSpatial Fig. Panel control's properties should be as follows: Propertie s Name Panel1 Panel2 Panel3 Panel4 pnlOperation pnlLegend pnlMap pnlAttribut s e Dock Top Left Fill Bottom Note: Set the border style of the panels to Fixed Single (Optional) 2. Add a menu strip control on the pnlOperations. Clear. Map Options. 1. Polyline. Exit Those implementations can be found in ‘Tutorial 2’. Polygon Teva ~ Veluppillai Page 4 . 1 ) Add the map control on the pnlMap control and add legend control on the pnlLegend. Under the Map Options menu item create the following sub menu items: Default. Save Polyline Shapefile. Zoom In. Add a DataGridView on the pnlAttribute.Topology Teva ~ Veluppillai Page 5 . Zoom to Extent. Under the Polygon sub menu item create the following Sub menu items: Create Polygon Shapefile. Pan. and Print Map Under the Attribute Table Operations menu item create the following sub menu items: View Attribute table. Add the Map and legend controls on the form. Save Polygon Shapefile. Set its properties as follows: Name : dgvAttributeTable . Menu Items 3. 4.Controls DotSpatial. Measurement. Delete a column in the attribute table. 3. Set the map properties as follows: Dock = Fill.Symbology DotSpatial. Fig. Zoom Out.Introduction to Programming with DotSpatial Under the Point sub menu item create the following Sub menu items: Create Point Shapefile. Under the Polyline sub menu item create the following Sub menu items: Create Polyline Shapefile.Data DotSpatial. 5. Map and Legend control are located on the Toolbox under DotSpatial controls. Add a column in the attribute table. Dock = Fill Step 5: Write the code for implementing the map operations. Save the colum in ShapeFile.1 ) Import the following namespaces: VB Imports Imports Imports Imports DotSpatial. Information. Legend = Legend1 Set the legend properties as follows: Dock = Fill 4. Save Point Shapefile. Update attribute table in Shapefile. Export Attribute table to Excel. #endregion Write the following code in the "CreatePointShapeFileToolStripMenuItem_Click" event VB Private Sub CreatePointShapeFileToolStripMenuItem_Click(ByVal sender As System. VB 'which type of shapefile is created Dim shapeType As String #Region "Point shapefile class level variable" 'the new point feature set Dim pointF As New FeatureSet(FeatureType.Click 'Change the cursor style Teva ~ Veluppillai Page 6 . //the id of point int pointID = 0. Create a Point shapefile.EventArgs) Handles CreatePointShapeFileToolStripMenuItem.Point) 'the id of point Dim pointID As Integer = 0 'to differentiate the right and left mouse click Dim pointmouseClick As Boolean = False #End Region C# //which type of shapefile is created string shapeType. DotSpatial.Symbology.Controls. //to differentiate the right and left mouse click bool pointmouseClick = false. Declare the following class level variables. DotSpatial. #region Point ShapeFile class level variable //the new point feature set FeatureSet pointF = new FeatureSet(FeatureType. DotSpatial. ByVal e As System.Data.Point).Introduction to Programming with DotSpatial C# using using using using DotSpatial.Object.Topology. //add the featureSet as map layer MapPointLayer pointLayer = (MapPointLayer)map1.Columns.Symbology.Introduction to Programming with DotSpatial Map1.Cross 'set the shape type to the classlevel string variable 'we are going to use this variable in select case statement shapeType = "Point" 'set projection pointF.PointShape. 3) 'Set the symbolizer to the point layer pointLayer.LegendText = "point" 'Set left mouse click as true pointmouseClick = True End Sub C# private void createPointShapefileToolStripMenuItem_Click(object sender.Cursor = Cursors.Red. 3). DotSpatial.Symbolizer = symbol 'Set the legentText as point pointLayer.Layers.Symbolizer = symbol.Red.Add(column).Symbology.Layers.Ellipse. } Write the following code in the Map mouse down event. On the properties window select the event tab and on the event tab double click over the Mouse down. //set the shape type to the classlevel string variable //we are going to use this variable in select case statement shapeType = "Point". //Set the legentText as point pointLayer. pointF. //Set the symbolizer to the point layer pointLayer. Generate the Map1 mouse down event. //initialize the featureSet attribute table DataColumn column = new DataColumn("PointID"). DotSpatial.Projection 'initialize the featureSet attribute table Dim column As New DataColumn("PointID") pointF.Ellipse.Columns.PointShape.Projection.Add(column) 'add the featureSet as map layer Dim pointLayer As MapPointLayer = Map1. //Create a new symbolizer PointSymbolizer symbol = new PointSymbolizer(Color.Cursor = Cursors.Projection = Map1.Cross.LegendText = "point".DataTable. //set projection pointF. EventArgs e) { //Change the cursor style map1.Projection = map1. : Select the map control and press the F4 key for getting its properties window.Add(pointF) 'Create a new symbolizer Dim symbol As New PointSymbolizer(Color. Teva ~ Veluppillai Page 7 . //Set left mouse click as true pointmouseClick = true.Add(pointF).DataTable. Location) 'Create a new point 'Input parameter is clicked point coordinate Dim point As New DotSpatial.Left Then If (pointmouseClick) Then 'This method is used to convert the screen coordinate to map coordinate 'e. VB Select Case shapeType Case "Point" If e.Default pointmouseClick = False End If End Select Teva ~ Veluppillai Page 8 . Map mouse down event.Topology.Button = MouseButtons. Write the following code in the Map1_MouseDown event.location is the mouse click point on the map control Dim coord As Coordinate = Map1.DataRow("PointID") = pointID 'refresh the map Map1.AddFeature(point) 'increase the point id pointID = pointID + 1 'set the ID attribute currentFeature. Dim currentFeature As IFeature = pointF. 5.Introduction to Programming with DotSpatial Fig.Cursor = Cursors.ResetBuffer() End If Else Map1.PixelToProj(e.Point(coord) 'Add the point into the Point Feature 'assigning the point feature to IFeature because via it only we can set the attributes. SaveAs("point.shp". Teva ~ Veluppillai Page 9 .AddFeature(point).Location).Topology. } } else { //mouse right click map1.Button == MouseButtons. //refresh the map map1.location is the mouse click point on the map control Coordinate coord = map1. EventArgs e) { pointF.Cursor = Cursors.Object.Default. } break. Save a point shape file: Write the following code into SavePointShapeFileToolStripMenuItem_Click event.Cursor = Cursors.Arrow End Sub C# private void SavePointShapeFileToolStripMenuItem_Click(object sender.Left) { if ((pointmouseClick)) { //This method is used to convert the screen cordinate to map coordinate //e. //Create a new point //Input parameter is clicked point coordinate DotSpatial. true).ResetBuffer(). VB Private Sub SavePointShapeFileToolStripMenuItem_Click(ByVal sender As System. //set the ID attribute //currentFeature. //Add the point into the Point Feature //assigning the point feature to IFeature because via it only we can set the attributes.SaveAs("point. pointmouseClick = false.shp". //increase the point id pointID = pointID + 1.") Map1.Point(coord). IFeature currentFeature = pointF.PixelToProj(e.DataRow["PointID"] = pointID.Click pointF.Topology.Point point = new DotSpatial. True) MsgBox("The point shapefile has been saved. ByVal e As System.Introduction to Programming with DotSpatial C# switch (shapeType) { case "Point" : if (e.EventArgs) Handles SavePointShapeFileToolStripMenuItem. Show("The point shapefile has been saved. Dim linemouseClick As Boolean = False #End Region C# Teva ~ Veluppillai Page 10 . 6. map1.Line) Dim lineID As Integer = 0 'boolean variable for first time mouse click Dim firstClick As Boolean = False 'It controls the drawing the polyline after the polyline saved operation.Arrow.Introduction to Programming with DotSpatial MessageBox. Create a point shape file. VB #Region "Polyline shapefile class level variables" 'the line layer Dim lineLayer As MapLineLayer 'the line feature set Dim lineF As New FeatureSet(FeatureType. } Output of the above code: Fig.Cursor = Cursors. Declare the following class level variables. Create Polyline shapefile."). #endregion Write the following code into CreatePolylineShapeFileToolStripMenuItem_Click event VB Private Sub CreatePolylineShapeFileToolStripMenuItem_Click(ByVal sender As System.DataTable.Symbolizer = symbol lineLayer. 2) lineLayer.Introduction to Programming with DotSpatial #region Polyline ShapeFile class level variables MapLineLayer lineLayer = default(MapLineLayer). //It controls the drawing the polyline after the polyline saved operation. //the line feature set FeatureSet lineF = new FeatureSet(FeatureType.Contains("LineID")) Then lineF. ByVal e As System.EventArgs) Handles CreatePolylineShapeFileToolStripMenuItem.LegendText = "line" firstClick = True linemouseClick = true.Blue. //boolean variable for first time mouse click bool firstClick = false.Cursor = Cursors.Line).Cross 'set shape type shapeType = "line" 'set projection lineF. End Sub C# Teva ~ Veluppillai Page 11 .Columns.Add(column) End If 'add the featureSet as map layer lineLayer = Map1.Projection 'initialize the featureSet attribute table Dim column As New DataColumn("LineID") If Not (lineF.Layers.Projection = Map1.Object.DataTable. int lineID = 0.Columns.Click 'initialize polyline feature set Map1. bool linemouseClick = false.Add(lineF) Dim symbol As New LineSymbolizer(Color. Contains("LineID")) { lineF. //Set the symbolizer to the line feature.Projection. } //add the featureSet as map layer lineLayer = (MapLineLayer)map1.Blue. EventArgs e) { //Change the mouse cursor map1.DataTable.Projection = map1. LineSymbolizer symbol = new LineSymbolizer(Color.Cross.PixelToProj(e. } linemouseClick = true. //set shape type shapeType = "line". 'We need to pass collection of list coordinates Dim lineGeometry As New LineString(lineArray) Teva ~ Veluppillai Page 12 .Add(column).LegendText = "line". 'In List we need not define the size and also 'Here this list will store the Coordinates 'We are going to store the mouse click coordinates into this array.Cursor = Cursors. firstClick = true.Columns.Layers. VB Case "line" If e.Button = MouseButtons.DataTable.Location) If (linemouseClick) Then 'first time left click .Columns.Add(lineF). //initialize the featureSet attribute table DataColumn column = new DataColumn("LineID").Left Then 'left click .fill array of coordinates 'coordinate of clicked point Dim coord As Coordinate = Map1. Write the following code in the Map1_MouseDown event. lineLayer. if (!lineF.Symbolizer = symbol. //set projection lineF. Dim lineArray As New List(Of Coordinate) 'Create an instance for LineString class.Introduction to Programming with DotSpatial private void CreatePolylineShapeFileToolStripMenuItem_Click(object sender. 2). lineLayer.create empty line feature If firstClick Then 'Create a new List called lineArray. Button == MouseButtons.reset first mouse click firstClick = True Map1. //set the line feature attribute Teva ~ Veluppillai Page 13 .fill array of coordinates //coordinate of clicked point Coordinate coord = map1.Add(coord) 'set the line feature attribute lineID = lineID + 1 lineFeature.ResetBuffer() End If End If End If Else 'right click . //This list will store the Coordinates //We are going to store the mouse click coordinates into this array.Add(coord) 'refresh the map if line has 2 or more points If existingFeature.InitializeVertices() Map1. //Create an instance for LineString class.Features(lineF. List<Coordinate> lineArray = new List<Coordinate>().create empty line feature if (firstClick) { //Create a new List called lineArray.add points to the existing feature Dim existingFeature As IFeature = lineF.Count .AddFeature(lineGeometry) 'add first coordinate to the line feature lineFeature.ResetBuffer() End If C# case "line": if (e.Location).1) existingFeature.Coordinates.Coordinates.Coordinates.Features.Coordinates.Count >= 2 Then lineF.PixelToProj(e.Left) { //left click .Add(coord).AddFeature(lineGeometry). //Add the linegeometry to line feature IFeature lineFeature = lineF.Introduction to Programming with DotSpatial 'Add the linegeometry to line feature Dim lineFeature As IFeature = lineF. //We need to pass collection of list coordinates LineString lineGeometry = new LineString(lineArray).DataRow("LineID") = lineID firstClick = False Else 'second or more clicks . //add first coordinate to the line feature lineFeature. if (linemouseClick) { //first time left click . firstClick = false.Arrow linemouseClick = False.DataRow["LineID"] = lineID. } //refresh the map if line has 2 or more points if (existingFeature.reset first mouse click firstClick = true. map1.shp".Coordinates. true).SaveAs("c:\MW\line. } else { //second or more clicks . linemouseClick = false. lineFeature.Cursor = Cursors.shp". } break. map1.Arrow.Click lineF.Count >= 2) { lineF.1].Introduction to Programming with DotSpatial lineID = lineID + 1.Coordinates.Cursor = Cursors. True) MsgBox("The line shapefile has been saved in C:\MW\") Map1.Add(coord).Object. map1.EventArgs) Handles SavePolylineShapeFileToolStripMenuItem.Features. MessageBox.Count . } } } else { //right click . existingFeature. EventArgs e) { lineF.ResetBuffer().add points to the existing feature IFeature existingFeature = lineF.Features[lineF.SaveAs("c:\\MW\\line.InitializeVertices(). ByVal e As System. End Sub C# private void savePolylineShapefileToolStripMenuItem_Click(object sender. Save the Polyline shapefile VB Private Sub SavePolylineShapeFileToolStripMenuItem_Click(ByVal sender As System.ResetBuffer(). } } Output of the above code Teva ~ Veluppillai Page 14 .Show("The line shapefile has been saved in C:\\MW\\"). bool polygonmouseClick = false.Polygon). #endregion Teva ~ Veluppillai Page 15 .Polygon) Dim polygonID As Integer = 0 Dim polygonmouseClick As Boolean = False #End Region C# #region Polygon ShapeFile class level variables FeatureSet polygonF = new FeatureSet(FeatureType.Introduction to Programming with DotSpatial Fig. int polygonID = 0. Create a polyline shapefile. Declare the following class level variables. VB #Region "Polygon shapefile class level variables" 'the polygon feature set Dim polygonF As New FeatureSet(FeatureType. Create Polygon shapefile. 7. Click 'initialize polyline feature set Map1.Cursor = Cursors.Cross.DataTable.Object.Layers.Contains("PolygonID")) { Teva ~ Veluppillai Page 16 . EventArgs e) { //initialize polyline feature set map1.Cursor = Cursors. ByVal e As System.Projection.Projection = map1. if (!polygonF. //set projection polygonF. //set shape type shapeType = "polygon".Columns. //initialize the featureSet attribute table DataColumn column = new DataColumn("PolygonID").DataTable.Projection = Map1.EventArgs) Handles CreatePolygonShapeFileToolStripMenuItem.Projection 'initialize the featureSet attribute table Dim column As New DataColumn("PolygonID") polygonF.Columns.Add(polygonF) 'set a symbology Dim symbol As New PolygonSymbolizer(Color.LegendText = "polygon" firstClick = True polygonmouseClick = True End Sub C# private void CreatePolygonShapeFileToolStripMenuItem_Click(object sender.Green) polygonLayer.Introduction to Programming with DotSpatial Write the following code into CreatePolygonShapeFileToolStripMenuItem_Click event VB Private Sub CreatePolygonShapeFileToolStripMenuItem_Click(ByVal sender As System.Add(column) 'add the featureSet as map layer Dim polygonLayer As MapPolygonLayer = Map1.Symbolizer = symbol 'add the legend text polygonLayer.Cross 'set shape type shapeType = "polygon" 'set projection polygonF. Coordinates.Coordinates.1) existingFeature. PolygonSymbolizer symbol = new PolygonSymbolizer(Color.Add(polygonF).Coordinates.LegendText = "polygon".Layers.Left Then 'left click . VB Case "polygon" If e.add points to the existing feature Dim existingFeature As IFeature = polygonF.Green).AddFeature(polygonGeometry) 'add first coordinate to the polygon feature polygonFeature. polygonLayer. } //add the featureSet as map layer MapPolygonLayer polygonLayer = (MapPolygonLayer)map1.Add(column). 'We pass the polygon List to the constructor of this class Dim polygonGeometry As New LinearRing(polygonArray) 'Add the polygonGeometry instance to PolygonFeature Dim polygonFeature As IFeature = polygonF. 'Here this list will store the Coordinates 'We are going to store the mouse click coordinates into this array.DataRow("PolygonID") = polygonID firstClick = False Else 'second or more clicks .ResetBuffer() End If Teva ~ Veluppillai Page 17 .DataTable.Symbolizer = symbol.Button = MouseButtons.Introduction to Programming with DotSpatial polygonF.Columns.InitializeVertices() Map1.create empty line feature If firstClick Then 'Create a new List called polygonArray.Add(coord) 'set the polygon feature attribute polygonID = polygonID + 1 polygonFeature.Features(polygonF. } Write the following code in the Map1_MouseDown event.Features.fill array of coordinates Dim coord As Coordinate = Map1. Dim polygonArray As New List(Of Coordinate) 'Create an instance for LinearRing class.Add(coord) 'refresh the map if line has 2 or more points If existingFeature. polygonmouseClick = true. polygonLayer.Count .PixelToProj(e.Count >= 3 Then 'refresh the map polygonF. firstClick = true.Location) If (polygonmouseClick) Then 'first time left click . //Create an instance for LinearRing class. List<Coordinate> polygonArray = new List<Coordinate>().reset first mouse click firstClick = True Map1. polygonFeature.Coordinates. //add first coordinate to the polygon feature polygonFeature.Coordinates.DataRow["PolygonID"] = polygonID.Features.Coordinates.Arrow End If C# case "polygon": if (e. //this list will store the Coordinates //We are going to store the mouse click coordinates into this array.Left) { //left click .Count >= 3) { //refresh the map Teva ~ Veluppillai Page 18 . //We pass the polygon List to the constructor of this class LinearRing polygonGeometry = new LinearRing(polygonArray). //Add the polygonGeometry instance to PolygonFeature IFeature polygonFeature = polygonF.create empty line feature if (firstClick) { //Create a new List called polygonArray.Cursor = Cursors.add points to the existing feature IFeature existingFeature = (IFeature)polygonF.fill array of coordinates Coordinate coord = map1.PixelToProj(e. if (polygonmouseClick) { //first time left click .Features[polygonF.Count . //set the polygon feature attribute polygonID = polygonID + 1.1].Location).Add(coord).AddFeature(polygonGeometry). existingFeature.Introduction to Programming with DotSpatial End If End If Else 'right click . firstClick = false. } else { //second or more clicks .Add(coord).Button == MouseButtons. //refresh the map if line has 2 or more points if (existingFeature. shp". map1.ResetBuffer().InitializeVertices().Introduction to Programming with DotSpatial } polygonF. EventArgs e) { polygonF. true).EventArgs) Handles SavePolygonShapeFileToolStripMenuItem.SaveAs("c:\MW\polygon. Save the Polygon shapefile VB Private Sub SavePolygonShapeFileToolStripMenuItem_Click(ByVal sender As System. map1."). } break.reset first mouse click firstClick = true.Arrow polygonmouseClick = False End Sub C# private void SavePolygonShapeFileToolStripMenuItem_Click(object sender.shp". MessageBox.Click polygonF.SaveAs("c:\\MW\\polygon. } Output of the above code Teva ~ Veluppillai Page 19 . polygonmouseClick = false.Object.Arrow. True) MsgBox("The polygon shapefile has been saved in C:\MW\") Map1.Cursor = Cursors. ByVal e As System.Show("The polygon shapefile has been saved.Cursor = Cursors. } } } else { //right click . The following code shows the all different shape operations. ByVal e As System.Left Then If (pointmouseClick) Then 'This method is used to convert the screen cordinate to map coordinate 'e.Point(coord) attributes. VB Private Sub Map1_MouseDown(ByVal sender As Object. 8.MouseEventArgs) Handles Map1.) 'Add the point into the Point Feature 'Assigning the point feature to IFeature (Because via it only we can set the Teva ~ Veluppillai Page 20 .Location) 'Create a new point 'Input parameter is clicked point coordinate Dim point As New DotSpatial.location is the mouse click point on the map control Dim coord As Coordinate = Map1.MouseDown Select Case shapeType Case "Point" If e.Forms.Windows. Map1 mouse down event complete code: In the above examples the same event is used to implement different shape functionalities.PixelToProj(e. So.Introduction to Programming with DotSpatial Fig.Topology. Create a polygon shapefile. the following code is the complete code for Map1 mouse down event.Button = MouseButtons. create empty line feature If firstClick Then 'Create a new List called lineArray. Dim lineArray As New List(Of Coordinate) 'Create an instance for LineString class.InitializeVertices() Map1.reset first mouse click Teva ~ Veluppillai Page 21 .Coordinates.Location) If (linemouseClick) Then 'first time left click .Features(lineF.Coordinates.PixelToProj(e.ResetBuffer() End If End If End If Else 'right click .Coordinates.Cursor = Cursors.Features.Count >= 2 Then lineF.Count .fill array of coordinates 'coordinate of clicked point Dim coord As Coordinate = Map1. 'In List we need not define the size and also 'Here this list will store the Coordinates 'We are going to store the mouse click coordinates into this array.DataRow("LineID") = lineID firstClick = False Else 'second or more clicks .Default pointmouseClick = False End If Case "line" If e.add points to the existing feature Dim existingFeature As IFeature = lineF. 'We need to pass collection of list coordinates Dim lineGeometry As New LineString(lineArray) 'Add the linegeometry to line feature Dim lineFeature As IFeature = lineF.Add(coord) 'refresh the map if line has 2 or more points If existingFeature.Introduction to Programming with DotSpatial Dim currentFeature As IFeature = pointF.Left Then 'left click .ResetBuffer() End If Else 'mouse right click Map1.DataRow("PointID") = pointID 'refresh the map Map1.Button = MouseButtons.1) existingFeature.AddFeature(lineGeometry) 'add first coordinate to the line feature lineFeature.Add(coord) 'set the line feature attribute lineID = lineID + 1 lineFeature.AddFeature(point) 'increase the point id pointID = pointID + 1 'set the ID attribute currentFeature. ResetBuffer() End If End If End If Else 'right click .ResetBuffer() End If Case "polygon" If e.fill array of coordinates Dim coord As Coordinate = Map1.Left Then 'left click .Arrow End If End Select End Sub C# Teva ~ Veluppillai Page 22 .Count >= 3 Then 'refresh the map polygonF.Coordinates.Introduction to Programming with DotSpatial firstClick = True Map1.Coordinates. 'Here this list will store the Coordinates 'We are going to store the mouse click coordinates into this array.add points to the existing feature Dim existingFeature As IFeature = polygonF.AddFeature(polygonGeometry) 'add first coordinate to the polygon feature polygonFeature.1) existingFeature.Add(coord) 'set the polygon feature attribute polygonID = polygonID + 1 polygonFeature.Add(coord) 'refresh the map if line has 2 or more points If existingFeature.Features.DataRow("PolygonID") = polygonID firstClick = False Else 'second or more clicks . 'We pass the polygon List to the constructor of this class Dim polygonGeometry As New LinearRing(polygonArray) 'Add the polygonGeometry instance to PolygonFeature Dim polygonFeature As IFeature = polygonF.PixelToProj(e.Count . Dim polygonArray As New List(Of Coordinate) 'Create an instance for LinearRing class.reset first mouse click firstClick = True Map1.create empty line feature If firstClick Then 'Create a new List called polygonArray.Coordinates.InitializeVertices() Map1.Cursor = Cursors.Features(polygonF.Location) If (polygonmouseClick) Then 'first time left click .Button = MouseButtons. Location).PixelToProj(e. //set the ID attribute currentFeature.location is the mouse click point on the map control Coordinate coord = map1.Left) { //left click . //This list will store the Coordinates //We are going to store the mouse click coordinates into this array.PixelToProj(e.Location).Cursor = Cursors.Default.Point point = new DotSpatial. } //refresh the map map1.ResetBuffer().DataRow["PointID"] = pointID.AddFeature(point).Topology.Button == MouseButtons. MouseEventArgs e) { switch (shapeType) { case "Point" : if (e.Point(coord).create empty line feature if (firstClick) { //Create a new List called lineArray.fill array of coordinates //coordinate of clicked point Coordinate coord = map1.Topology.Introduction to Programming with DotSpatial private void map1_MouseDown(object sender. //Create a new point //Input parameter is clicked point coordinate DotSpatial.Left) { if ((pointmouseClick)) { //This method is used to convert the screen cordinate to map coordinate //e. //Add the point into the Point Feature //assigning the point feature to IFeature because via it only we can set the attributes.Button == MouseButtons. } else { //mouse right click map1. Teva ~ Veluppillai Page 23 . pointmouseClick = false. IFeature currentFeature = pointF. } break. //increase the point id pointID = pointID + 1. if (linemouseClick) { //first time left click . case "line": if (e. AddFeature(lineGeometry).Coordinates.DataRow["LineID"] = lineID.Introduction to Programming with DotSpatial List<Coordinate> lineArray = new List<Coordinate>(). //Add the linegeometry to line feature IFeature lineFeature = lineF.create empty line feature if (firstClick) { //Create a new List called polygonArray.Coordinates.Add(coord). case "polygon": if (e.reset first mouse click firstClick = true. //We need to pass collection of list coordinates LineString lineGeometry = new LineString(lineArray).Features. existingFeature.Left) { //left click .Add(coord).add points to the existing feature IFeature existingFeature = lineF. } else { //second or more clicks . lineFeature. map1.Count >= 2) { lineF. if (polygonmouseClick) { //first time left click . //add first coordinate to the line feature lineFeature.1]. map1.ResetBuffer().Features[lineF. //this list will store the Coordinates //We are going to store the mouse click coordinates into this array. //set the line feature attribute lineID = lineID + 1. } //refresh the map if line has 2 or more points if (existingFeature.Location).Coordinates. Teva ~ Veluppillai Page 24 . } break.InitializeVertices(). firstClick = false.PixelToProj(e.Button == MouseButtons.fill array of coordinates Coordinate coord = map1. } } } else { //right click .ResetBuffer().Count . //Create an instance for LineString class. VB Private Sub ViewAttrbuteTableToolStripMenuItem_Click(ByVal sender As System.Coordinates.InitializeVertices().DataRow["PolygonID"] = polygonID. //We pass the polygon List to the constructor of this class LinearRing polygonGeometry = new LinearRing(polygonArray). ByVal e As System.Click Teva ~ Veluppillai Page 25 .Introduction to Programming with DotSpatial List<Coordinate> polygonArray = new List<Coordinate>().Add(coord).Count >= 3) { //refresh the map polygonF.Coordinates. } Attribute table related operations View the attribute table from the US States shapefile.AddFeature(polygonGeometry). //set the polygon feature attribute polygonID = polygonID + 1.1]. existingFeature.reset first mouse click firstClick = true. polygonFeature. //refresh the map if line has 2 or more points if (existingFeature.EventArgs) Handles ViewAttrbuteTableToolStripMenuItem.Features[polygonF.ResetBuffer().add points to the existing feature IFeature existingFeature = (IFeature)polygonF.Add(coord). map1.Features. //add first coordinate to the polygon feature polygonFeature.Coordinates. } else { //second or more clicks . } } } } } else { //right click .Count . firstClick = false. } break.Object. //Create an instance for LinearRing class. //Add the polygonGeometry instance to PolygonFeature IFeature polygonFeature = polygonF. ") End If End Sub C# private void ViewAttrbuteTableToolStripMenuItem_Click(object sender. } else { //Get the shapefile's attribute table to our datatable dt dt = stateLayer.Count > 0 Then Dim stateLayer As MapPolygonLayer stateLayer = TryCast(Map1.DataSet.Show("The layer is not a polygon layer.DataSet. if (stateLayer == null) { MessageBox.DataSource = dt.1.Layers. } } 5.Introduction to Programming with DotSpatial 'Declare a datatable Dim dt As DataTable If Map1.Layers.Data.Show("Please add a layer to the map."). if (map1.DataSource = dt End If Else MessageBox. //Set the datagridview datasource from datatable dt dgvAttributeTable.") Else 'Get the shapefile's attribute table to our datatable dt dt = stateLayer. } } else { MessageBox. stateLayer = (MapPolygonLayer)map1.DataTable 'Set the datagridview datasource from datatable dt dgvAttributeTable.Show("The layer is not a polygon layer.Show("Please add a layer to the map.Count > 0) { MapPolygonLayer stateLayer = default(MapPolygonLayer).").1) Output of the above code Teva ~ Veluppillai Page 26 .Layers(0).Layers[0].DataTable. EventArgs e) { //Declare a datatable System. MapPolygonLayer) If stateLayer Is Nothing Then MessageBox.DataTable dt = null. Layers(0).Count > 0 Then Dim stateLayer As MapPolygonLayer stateLayer = TryCast(Map1. Add a new column into the attribute table.EventArgs) Handles CreateAColumInAttributeTableToolStripMenuItem.Introduction to Programming with DotSpatial Fig.Object. In the following example the new column name is "PercentMales" VB Private Sub CreateAColumInAttributeTableToolStripMenuItem_Click(ByVal sender As System. 9.Add(column) 'calculate values For Each row As DataRow In dt. MapPolygonLayer) If stateLayer Is Nothing Then MessageBox. View attribute table of the shapefile.Columns.DataSet.Rows Dim males As Double = row("males") Dim females As Double = row("females") Dim malesPercentage As Double = (males / (males + females)) * 100 row("PercentMales") = malesPercentage Teva ~ Veluppillai Page 27 . ByVal e As System.Show("The layer is not a polygon layer.Layers.") Else 'Get the shapefile's attribute table to our datatable dt dt = stateLayer.DataTable 'Add new column Dim column As New DataColumn("PercentMales") dt.Click 'Declare a datatable Dim dt As DataTable If Map1. //calculate values foreach (DataRow row in dt.Introduction to Programming with DotSpatial Next 'Set the datagridview datasource from datatable dt dgvAttributeTable.ToDouble(row["females"]). //Assign the mappolygon layer from the map stateLayer = map1. //check the layers if (map1.Show("Please add a layer to the map.Add(column). } } else { MessageBox.").") End If End Sub C# private void CreateAColumInAttributeTableToolStripMenuItem_Click(object sender. if (stateLayer == null) { MessageBox.Layers.Layers[0] as MapPolygonLayer.DataSet.Show("Please add a layer to the map. } else { //Get the shapefile's attribute table to our datatable dt dt = stateLayer.Show("The layer is not a polygon layer. } } Output of the above code.DataSource = dt. dt. Teva ~ Veluppillai Page 28 .Columns.DataSource = dt End If Else MessageBox.DataTable.Count > 0) { //Declare a mappolygon layer MapPolygonLayer stateLayer = default(MapPolygonLayer).Rows) { double males = Convert. //Add new column DataColumn column = new DataColumn("PercentMales")."). row["PercentMales"] = malesPercentage. double females = Convert. double malesPercentage = (males / (males + females)) * 100.Data. EventArgs e) { //Declare a datatable System. } //Set the datagridview datasource from datatable dt dgvAttributeTable.ToDouble(row["males"]).DataTable dt = null. Introduction to Programming with DotSpatial Fig. ByVal e As System. EventArgs e) { if (map1.Layers(0). MapPolygonLayer) If stateLayer Is Nothing Then MessageBox.") End If End Sub C# private void SaveTheColumInShapeFileToolStripMenuItem_Click(object sender.Object.Save() End If Else MessageBox.Click If Map1.EventArgs) Handles SaveTheColumInShapeFileToolStripMenuItem.") Else stateLayer. Update the shapefile's attribute table. Add a new column PercentMales in the attribute table.Layers. VB Private Sub SaveTheColumInShapeFileToolStripMenuItem_Click(ByVal sender As System.Show("The layer is not a polygon layer.Count > 0 Then Dim stateLayer As MapPolygonLayer stateLayer = TryCast(Map1.Layers.Count > 0) { Teva ~ Veluppillai Page 29 .DataSet.Show("Please add a layer to the map. 10. Layers. stateLayer = map1. Teva ~ Veluppillai Page 30 .Save().DataTable 'Remove a column dt."). if (stateLayer == null) { MessageBox. } } else { MessageBox.Remove("PercentMales") 'Set the datagridview datasource from datatable dt dgvAttributeTable.Show("Please add a layer to the map. In the following example "PercentMales" column will be deleted. VB Private Sub DeleteColumnInAttributeTableToolStripMenuItem_Click(ByVal sender As System.Layers[0] as MapPolygonLayer.Layers(0).Count > 0 Then Dim stateLayer As MapPolygonLayer stateLayer = TryCast(Map1. ByVal e As System.Layers[0] as MapPolygonLayer. } } Delete the attribute column from the attribute table.") End If End Sub C# private void DeleteColumnInAttributeTableToolStripMenuItem_Click(object sender.EventArgs) Handles DeleteColumnInAttributeTableToolStripMenuItem. } else { stateLayer.") Else 'Get the shapefile's attribute table to our datatable dt dt = stateLayer.Show("The layer is not a polygon layer.DataSet.Data.Object.Show("The layer is not a polygon layer.Layers.DataSet.Count > 0) { MapPolygonLayer stateLayer = default(MapPolygonLayer).Columns.Introduction to Programming with DotSpatial MapPolygonLayer stateLayer = default(MapPolygonLayer).Click 'Declare a datatable Dim dt As DataTable If Map1.Show("Please add a layer to the map."). stateLayer = map1.DataSource = dt End If Else MessageBox.DataTable dt = null. if (map1. EventArgs e) { //Declare a datatable System. MapPolygonLayer) If stateLayer Is Nothing Then MessageBox. Show("The layer is not a polygon layer.Columns.").Interop. //Set the datagridview datasource from datatable dt dgvAttributeTable.Click 'Declare a datatable Dim dt As DataTable If Map1.Remove("PercentMales"). //Remove a column dt. VB Private Sub ExportAttributeTableToExcelToolStripMenuItem_Click(ByVal sender As System.Introduction to Programming with DotSpatial if (stateLayer == null) { MessageBox.") End If End Sub C# Teva ~ Veluppillai Page 31 .Excel Write the following code into the ExportAttributeTableToExcelToolStripMenuItem_Click event.DataTable 'Call the sub ExportToExcel 'This sub procedure expects a datatable as an input ExportToExcel(dt) End If Else MessageBox.Count > 0 Then Dim stateLayer As MapPolygonLayer stateLayer = TryCast(Map1."). } else { //Get the shapefile's attribute table to our datatable dt dt = stateLayer.DataSet. } } Export an attribute table to Excel datasheet. MapPolygonLayer) If stateLayer Is Nothing Then MessageBox. Right click over the project on the solution explorer.DataTable.DataSet.") Else 'Get the shapefile's attribute table to our datatable dt dt = stateLayer.EventArgs) Handles ExportAttributeTableToExcelToolStripMenuItem.Object. ByVal e As System.Layers(0).Show("Please add a layer to the map. } } else { MessageBox.Layers.Office.Show("Please add a layer to the map.DataSource = dt.Show("The layer is not a polygon layer. On the context menu select the add reference and add the .NET reference: Microsoft. Layers. if (map1. stateLayer = map1. } else { //Get the shapefile's attribute table to our datatable dt dt = stateLayer.Worksheets(1).</remarks> Private Sub ExportToExcel(ByVal objDT As DataTable) Dim Excel As Object = CreateObject("Excel.Show("The layer is not a polygon layer.Data.Introduction to Programming with DotSpatial private void ExportAttributeTableToExcelToolStripMenuItem_Click(object sender. VB ''' <summary> ''' This sub method is used to create an excel worksheet from the attribute table ''' </summary> ''' <param name="objDT">attribute table as a datatable input</param> ''' <remarks> Click the COM tab of the Add Reference dialog box.Select() Teva ~ Veluppillai Page 32 . MsgBoxStyle.Add() .Critical) Return End If Try With Excel .Application") Dim strFilename As String Dim intCol.").Layers[0] as MapPolygonLayer. } } Write the following sub method for getting an excel datasheet output from an attribute table.DataSet. intRow As Integer 'path for storing excel datasheet Dim strPath As String = "C:\2009 Falls\" If Excel Is Nothing Then MsgBox("It appears that Excel is not installed on this machine.".SheetsInNewWorkbook = 1 .DataTable.Show("Please add a layer to the map. This operation requires MS Excel to be installed on this machine.Count > 0) { MapPolygonLayer stateLayer = default(MapPolygonLayer). if (stateLayer == null) { MessageBox. and find Microsoft Excel 14 Object Library. } } else { MessageBox.").Workbooks. //Call the sub ExportToExcel //This sub procedure expects a datatable as an input ExportToExcel(dt).DataTable dt = null. EventArgs e) { //Declare a datatable System. cells(1.Process.Count .Runtime.cells(2.EntireRow.1 intI = 3 For intRow = 0 To objDT. strPath.Length.cells(2. 1) <> "\" Then strPath = strPath & "\" End If strFilename = strPath & "AttributeTable.Columns.1 .Font.Bold = True 'Add the column names from the attribute table to excel worksheet Dim intI As Integer = 1 For intCol = 0 To objDT.Bold = True intI += 1 Next 'Add the data row values from the attribute table to ecxel worksheet intI = 3 Dim intK As Integer = 1 For intCol = 0 To objDT.Count .Marshal. MsgBoxStyle. intI).xls" .Information) Catch ex As Exception MsgBox(ex.cells(1. 1).Rows.Font.Cells(intI.InteropServices.Columns(intCol).ColumnName .Kill() Next End Sub C# /// <summary> /// This sub method is used to create an excel worksheet from the attribute table /// </summary> /// <param name="objDT">attribute table as a datatable input</param> /// <remarks>Click the COM tab of the Add Reference dialog box. 1).value = objDT.Worksheet.GetProcessesByName("EXCEL") For Each i As Process In pro i.SaveAs(strFilename) End With System.ActiveCell.Introduction to Programming with DotSpatial .EntireRow.Count .Diagnostics. and find Microsoft Excel 14 Object Library. intK).Columns.value = "Attribute table" 'Heading of the excel file .Value = objDT.Message) End Try ' The excel is created and opened for insert value.ItemArray(intCol) intI += 1 Next intK += 1 Next If Mid$(strPath. We most close this excel using this system Dim pro() As Process = System. intI).</remarks> Teva ~ Veluppillai Page 33 .Rows(intRow).1 .ReleaseComObject(Excel) Excel = Nothing MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'". Workbooks.Cells[intI.Cells[1.SheetsInNewWorkbook = 1. Microsoft.Office.xls". //path for storing excel datasheet string strPath = "C:\\2009 Falls\\".Office.EntireRow. 1].ItemArray[intCol].1.Application(). intRow <= objDT. if (xlApp == null) { MessageBox. Teva ~ Veluppillai Page 34 .OK.Substring(strPath. xlApp. xlApp. } //Add the data row values from the attribute table to ecxel worksheet intI = 3. } intK += 1. } try { //var _with1 = Microsoft. "". intCol <= objDT.1.Cells[2.Excel.Add(). for (intCol = 0. intK].Columns. This operation requires MS Excel to be installed on this machine. intI += 1. //Heading of the excel file xlApp. 1].Bold = true. string strFilename = null.1.Interop.Worksheets[1].".Application xlApp = new Microsoft.Interop.Select().Length .Columns.Excel. int intCol = 0.Count .Data. //Add the column names from the attribute table to excel worksheet int intI = 1.1. intCol <= objDT.ColumnName.Columns[intCol]. xlApp. xlApp.Cells[2. 1) != "\\") { strPath = strPath + "\\". intI].Application(). intI += 1.Count . } strFilename = strPath + "AttributeTable. int intK = 1.Exclamation).Show("It appears that Excel is not installed on this machine. for (intRow = 0.value = objDT. for (intCol = 0. } if (strPath.Bold = true.Application(). MessageBoxButtons.Count . intI]. MessageBoxIcon. intRow++) { xlApp.Introduction to Programming with DotSpatial private void ExportToExcel(System.Cells[1.Font. int intRow = 0.Rows. intCol++) { xlApp.Rows[intRow]. xlApp.DataTable objDT) { //excel = new Excel.Font.Interop.Excel.EntireRow. return.Office.Value = objDT. intCol++) { intI = 3.value = "Attribute table". MessageBoxIcon.GetProcessesByName("EXCEL").Show("Data's are exported to Excel Succesfully in '" + strFilename + "'".Process i in pro) { i.Diagnostics.InteropServices.Process[] pro = (System.MapControl = Map1 frm.Introduction to Programming with DotSpatial xlApp.ReleaseComObject(xlApp).EventArgs) Handles PrintMapToolStripMenuItem. EventArgs e) { DotSpatial.Diagnostics.Worksheet. frm. We most close this excel using this system System.Diagnostics.Runtime.Controls. } Output of the above code is follows: Teva ~ Veluppillai Page 35 .Show().LayoutForm frm = new DotSpatial.Marshal.SaveAs(strFilename). foreach (System.ActiveCell. MessageBoxButtons.LayoutForm frm.Show(ex. } // The excel is created and opened for insert value.Click Dim frm As New DotSpatial. } catch (Exception ex) { MessageBox.MapControl = map1.LayoutForm(). } } Printing a map in DotSpatial Write the following code into the PrintMapToolStripMenuItem_Click event VB Private Sub PrintMapToolStripMenuItem_Click(ByVal sender As System.Process.Message). "".Object.Controls.Diagnostics.Controls.OK. xlApp = null.Process[])System.Show() End Sub C# private void PrintMapToolStripMenuItem_Click(object sender. ByVal e As System.Kill(). System. MessageBox. frm.Information). Introduction to Programming with DotSpatial Teva ~ Veluppillai Page 36 .