Display your first map from sql server database using sharpmap, code C#

Topics: General Topics, SharpMap Project
Dec 11, 2012 at 12:13 AM

In the code below we are going to display a map from a sql server database using sharpmap. the code is written in C# with Visual Studio 2010.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using SharpMap;
using SharpMap.Geometries;
using SharpMap.Layers;
using SharpMap.Data.Providers;

namespace sqlcnx
    public partial class Form1 : Form
// we start with the connection string
       static string connstr = "user id=Youssef;password='';"+ 
//user id = name of your PC and because I use windows authentification I don't need passowrd

//write your PC name + \\SQL (my PC is YOUSSEF)

            "database=test;connection timeout=10";
//my database name is 'test' , the connection timeout is the time in second that the proram will waite for the server to connect before generating an exeption

   SqlConnection myConnection = new SqlConnection(connstr);
        Map map;
        VectorLayer vly= new VectorLayer("vly", new SharpMap.Data.Providers.SqlServer2008(connstr, "quartier", "shape", null));

// 'quartier' is the name of the table in my database and 'shape' represente the geometry column in that table
        public Form1() 

        private void Form1_Load(object sender, EventArgs e)
            map = new Map(pictureBox1.Size);
// we give the map the pictureBox size, don't forget to add a pictureBox to your form in the designer ;)

            vly.Style.EnableOutline = true;
            vly.Style.Outline = Pens.Black;
            vly.Style.Fill = Brushes.Red;
//the style of our vectorlayer color contour ..etc

           map.Layers.Add(vly); // add layer to the map
           map.ZoomToExtents(); //zoom to extentto see all the map
           map.BackColor = Color.White;
           pictureBox1.Image = map.GetMap();
//affect the map to the pictureBox


if you have errors make sure that you've added the sharpmap reference and switch the .Net framework 4

and Enjoy :)