View spatial data by SharpMap

This sample is about to display maps, which are in PostGis tables. There is a listbox, where the opened layers can be seen in. Maps are displayed in a SharpMap MapBox control.




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpMap;
using SharpMap.Forms;
using SharpMap.Layers;
using Npgsql;



namespace mapViewer
{
    public partial class frmMain : Form
    {
        NpgsqlConnectionStringBuilder cnsbuilder=new NpgsqlConnectionStringBuilder();
        const float zoom = 0.3F;
        public SharpMap.Forms.MapBox mapBox1 = new MapBox();
        //public SharpMap.Layers.LayerCollection MapLayers = new LayerCollection();

        public frmMain()
        {
            InitializeComponent();          
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            
            this.splitContainer1.Panel1.Controls.Add(this.mapBox1);
            //ls = new layerList(curMaps);  
            this.mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;
            this.mapBox1.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.mapBox1.Cursor = System.Windows.Forms.Cursors.Hand;
            this.mapBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.mapBox1.FineZoomFactor = 10D;
            this.mapBox1.Location = new System.Drawing.Point(0, 0);
            this.mapBox1.MapQueryMode = SharpMap.Forms.MapBox.MapQueryType.LayerByIndex;
            this.mapBox1.Name = "mapBox1";
            this.mapBox1.QueryGrowFactor = 5F;
            this.mapBox1.QueryLayerIndex = 0;
            this.mapBox1.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.ShowProgressUpdate = false;
            this.mapBox1.Size = new System.Drawing.Size(504, 460);
            this.mapBox1.TabIndex = 1;
            this.mapBox1.Text = "mapBox1";
            this.mapBox1.WheelZoomMagnitude = -2D;

            cnsbuilder.Host = "localhost";
            cnsbuilder.UserName = "elek";
            cnsbuilder.Password = "28milike";
            cnsbuilder.Database = "ed";
            loadTableNames();
            splitContainer1.SplitterDistance = splitContainer1.Width - splitContainer1.SplitterWidth;
        }
        


        private void loadTableNames()
        {
           //SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'

            using (NpgsqlConnection cnn = new NpgsqlConnection(cnsbuilder.ConnectionString))
            {
                cnn.Open();
                NpgsqlDataAdapter da = new NpgsqlDataAdapter("SELECT f_table_name FROM geometry_columns", cnn);
                //NpgsqlDataAdapter da = new NpgsqlDataAdapter("SELECT table_name FROM information_schema.tables WHERE table_schema='public'  AND table_type='BASE TABLE'", cnn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                foreach (DataRow row in dt.Rows)
                {
                    cmbTableNames.Items.Add(row[0]);
                }
            }
        }


        private DataTable loadTableData(string tableName)
        {
            using (NpgsqlConnection cnn = new NpgsqlConnection(cnsbuilder.ConnectionString))
            {
                cnn.Open();
                string sql = "select " + getNonGeoNames(tableName);
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, cnn);
                //NpgsqlDataAdapter da = new NpgsqlDataAdapter("SELECT * FROM " + tableName, cnn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }

        string getNonGeoNames(string tableName)
        {
            using (NpgsqlConnection cnn = new NpgsqlConnection(cnsbuilder.ConnectionString))
            {
                string columns = "";                
                cnn.Open();

                string sqlCommand = "SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name   = '" + tableName + "'";
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sqlCommand, cnn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                foreach (DataRow row in dt.Rows)
                {
                    if (row[0].ToString() != "geom")
                    {
                        if (row[0].ToString() != "gid") {columns += row[0].ToString() + ", ";}
                    }
                }
                columns=columns.TrimEnd(' ', ',');
                columns += " from " + tableName;
            return columns;
            }


        }

        private void cmbTableNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            //dgw.DataSource=loadTableData(cmbTableNames.SelectedItem.ToString());
            string layerName = cmbTableNames.SelectedItem.ToString();
            addDbLayer(layerName);
        }


        void addDbLayer(string layer_name)
        {
            string idColumn = "gid";
            SharpMap.Layers.VectorLayer lay1 = new SharpMap.Layers.VectorLayer(layer_name);
            lay1.DataSource = new SharpMap.Data.Providers.PostGIS(cnsbuilder.ConnectionString, layer_name, idColumn);
            Random rnd=new Random();
            int R=rnd.Next(0,255);
            int G=rnd.Next(0,255);
            int B=rnd.Next(0,255);
            Color col = Color.FromArgb(R, G, B);
            Brush brushColor = new SolidBrush(col);
            lay1.Style.Outline.Brush = brushColor;
            Color col2 = Color.FromArgb(255-R, 255-G, 255-B);
            Brush brushColor2 = new SolidBrush(col2);
            lay1.Style.Fill = brushColor2;
            lay1.Style.EnableOutline = true;
            mapBox1.Map.Layers.Add(lay1);
            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
            lstLayers.Items.Insert(0, lay1.LayerName); 
        }



        private void tsBconnect_Click(object sender, EventArgs e)
        {
            frmConnect con = new frmConnect();
            if (con.ShowDialog()==DialogResult.OK)
            {
                cnsbuilder = con.cnsb;
                loadTableNames();
            }
        }

        private void tsZoom2All_Click(object sender, EventArgs e)
        {
            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
        }

        private void tsSplitleft_Click(object sender, EventArgs e)
        {
            //splitContainer1.SplitterDistance = 0;
            splitterto("left");
        }

        private void tsSplitRight_Click(object sender, EventArgs e)
        {
            //splitContainer1.SplitterDistance = splitContainer1.Width - splitContainer1.SplitterWidth;
            splitterto("right");
        }

        private void tskozepre_Click(object sender, EventArgs e)
        {
            splitterto("half");
            //splitContainer1.SplitterDistance = (splitContainer1.Width - splitContainer1.SplitterWidth)/2;
        }



        private void tsRemoveLayer_Click(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex != -1)
            {
                mapBox1.Map.Layers.RemoveAt(lstLayers.Items.Count - lstLayers.SelectedIndex - 1);
                mapBox1.Refresh();
                lstLayers.Items.RemoveAt(lstLayers.SelectedIndex);
                dgw.DataSource = null;
            }
        }


        private void lstLayers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex !=-1)
            {
                SharpMap.Layers.LayerCollection MapLayers = new LayerCollection();
                MapLayers = mapBox1.Map.Layers;
                int currentIndex = lstLayers.SelectedIndex;
                string currentItem = lstLayers.SelectedItem.ToString();
                SharpMap.Layers.Symbolizer.PolygonalVectorLayer curLy = new SharpMap.Layers.Symbolizer.PolygonalVectorLayer(currentItem);
                SharpMap.Rendering.Symbolizer.BasicPolygonSymbolizer pgs = new SharpMap.Rendering.Symbolizer.BasicPolygonSymbolizer();
                pgs.Fill = Brushes.Aqua;
                pgs.Outline.Color = Color.Black;
                curLy.Symbolizer = pgs;
                //mapBox1.Map.Layers;
                mapBox1.Refresh();
            }
        }




        private void tsMoveDown_Click(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex != -1)
            {
                if (lstLayers.SelectedIndex < lstLayers.Items.Count - 1)
                {
                    SharpMap.Layers.LayerCollection MapLayers = new LayerCollection();
                    MapLayers = mapBox1.Map.Layers;
                    int currentIndex = lstLayers.SelectedIndex;
                    string currentItem=lstLayers.SelectedItem.ToString();
                    SharpMap.Layers.ILayer curLay = MapLayers[MapLayers.Count - currentIndex - 1];

                    mapBox1.Map.Layers.RemoveAt(MapLayers.Count - currentIndex - 1);
                    MapLayers = mapBox1.Map.Layers;

                    mapBox1.Map.Layers.Insert(MapLayers.Count - currentIndex - 1, curLay);
                    mapBox1.Refresh();

                    lstLayers.Items.RemoveAt(currentIndex);
                    lstLayers.Items.Insert(currentIndex + 1, currentItem);
                }
            }
        }

        private void tsMoveUp_Click(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex != -1)
            {
                if (lstLayers.SelectedIndex > 0)
                {
                    SharpMap.Layers.LayerCollection MapLayers = new LayerCollection();
                    MapLayers = mapBox1.Map.Layers;
                    int currentIndex = lstLayers.SelectedIndex;
                    string currentItem = lstLayers.SelectedItem.ToString();
                    SharpMap.Layers.ILayer curLay = MapLayers[MapLayers.Count - currentIndex - 1];

                    mapBox1.Map.Layers.RemoveAt(MapLayers.Count - currentIndex - 1);
                    mapBox1.Map.Layers.Insert(MapLayers.Count - currentIndex+1, curLay);
                    mapBox1.Refresh();
                    MapLayers = mapBox1.Map.Layers;

                    lstLayers.Items.RemoveAt(currentIndex);
                    lstLayers.Items.Insert(currentIndex-1, currentItem);
                }
            }
        }

        void splitterto(string flag)
        {
            if (flag == "half")
            {
                splitContainer1.SplitterDistance = (splitContainer1.Width - splitContainer1.SplitterWidth) / 2;
            }
            if (flag == "left")
            {
                splitContainer1.SplitterDistance = 0; 
            }
            if (flag == "right")
            {
                splitContainer1.SplitterDistance = splitContainer1.Width - splitContainer1.SplitterWidth;
                dgw.DataSource = null;
            }
        }

        private void lstLayers_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) 
            { 
                lstLayers.SelectedIndex = -1;
                dgw.DataSource = null;
                splitterto("right");
            }
        }

        private void tsShowTabular_Click(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex != -1)
            {
                dgw.DataSource = loadTableData(lstLayers.SelectedItem.ToString());
                splitterto("half");
                tsRecCount.Text = "Row count: " + (dgw.RowCount - 1).ToString();
                tsSelectedLayerName.Text = "         Layer name: " + lstLayers.SelectedItem.ToString();
            }
        }

        private void tsStyle_Click(object sender, EventArgs e)
        {
            if (lstLayers.SelectedIndex != -1)
            {
                switch (getLayerType(lstLayers.SelectedItem.ToString()))
                {

                    case "MULTIPOLYGON":
                        frmPolygonStyle frmmPgStyle = new frmPolygonStyle();
                        frmmPgStyle.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
                        frmmPgStyle.Location = splitContainer1.Location;
                        
                        if (frmmPgStyle.ShowDialog() == DialogResult.OK) 
                        {
                            ColorDialog cd = new ColorDialog();
                            if (cd.ShowDialog() == DialogResult.OK)
                            {

                            }
                        }
                        break;

                    case "POLYGON":
                        frmPolygonStyle frmPgStyle = new frmPolygonStyle();
                        frmPgStyle.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
                        frmPgStyle.Location = splitContainer1.Location;

                        if (frmPgStyle.ShowDialog() == DialogResult.OK)
                        {
                            ColorDialog cd = new ColorDialog();
                            if (cd.ShowDialog() == DialogResult.OK)
                            {

                            }
                        }
                        break;

                    case "POINT":

                        break;

                    case "LINE":

                        break;

                    case "unknown":
                        break;
                }
            }
        }


        string getLayerType(string layerName)
        {
            string lyType = "unknown";
            using (NpgsqlConnection cnn = new NpgsqlConnection(cnsbuilder.ConnectionString))
            {
                //cnn.Open();
                string sqlCom = "SELECT type FROM geometry_columns WHERE f_table_schema = 'public' AND f_table_name = '" + lstLayers.SelectedItem.ToString() + "' and f_geometry_column = 'geom'";
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sqlCom, cnn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                lyType = dt.Rows[0][0].ToString();
            }
            return lyType;
        }

    }
}