[GIS] How to use Sharpmap to display spatial data from MS SQL Server 2008

csharpmapsql server

Can anyone show me a step by step example on how to use Sharpmap to display MS SQL server spatial data using C# as the programming language?

Please note I have exploit some of the example online but nor seem to be displaying data from MS SQL server 2008.

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

            "server=YOUSSEF-PC\\SQL;"+
//write your PC name + \\SQL (my PC is YOUSSEF)

            "Trusted_Connection=yes;"+
            "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() 
        {
            InitializeComponent();
        }

        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
        }

    }
}

Best Answer

You need to specify an object id column! If you don't have one on your table, you need to add one (UINT).

You need to check your connection string. Is your SQL-Server instance really "YOUSSEF-PC\SQL"?
You can test if your connection works by invoking

System.Diagonstics.Debug.Assert(vly.GetFeatureCount() > 0);

Do you have geometry of geography objects in your table? If they are not geometry, you need to specify that in the constructor like

VectorLayer vly= new VectorLayer("vly", new SharpMap.Data.Providers.SqlServer2008(connstr, "quartier", "shape", "oid", SqlServerSpatialObjectType.Geography));