Tutorial 58: X/Y chart with databinding (C#)
« on: June 07, 2016, 01:57:54 AM »
This sample code will plot a scatter X/Y chart using data from a DataGridView and will show how to bind the control
so selections and modifications in either one are reflected on the other
.
 
Key aspects of this tutorial:
  • Change data in DataGridView and chart control will update automatically.
  • You can make a selection of cells in DataGridView and data will be highlighted in chart also.
  • You can move selection using mouse (press CONTROL and drag the point in chart)
  • You can make a selection of points in chart pressing CONTROL or SHIFT while moving the mouse over the chart.

Steps:

1. Create a new Windows application project (C#)
2. Add Crossing Charts Library to the toolbox pallete and drag it to Form1. Name it chart1.
3. Add a DataGridView control to the Form1.
4. Copy and paste de following code:

Code: [Select]
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrossingChartsLibrary;

namespace XYFomulaPlotting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Prepare the Data Grid View
            int rows = 20;
            int cols = 2;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            dataGridView1.Columns.Clear();
            dataGridView1.Columns.Add("X", "X");
            dataGridView1.Columns.Add("Y", "Y");
            dataGridView1.Rows.Add(rows);
            int y = 0;
            Random rnd = new Random();
            for (int r = 1; r <= rows; r++)
            {
                dataGridView1.Rows[r - 1].HeaderCell.Value = r.ToString();
                for (int k = 1; k <= cols; k++)
                {
                    dataGridView1.Rows[r - 1].Cells[k - 1].Value = y;
                    y += rnd.Next(10) - 5;
                }
            }

            // Configure chart
            chart1.Title = "X/Y Databinding Demo";
            chart1.Style = STYLE2D3D.STYLE2D_XY;
            chart1.ShowValues = false;
            chart1.ShowDataTable = false;
            chart1.XAxisLabelsRotated = true;
            chart1.LegendAlignment = STYLEALIGNMENT.STYLEALIGNMENT_BOTTOM_CENTER;

            // Databind
            chart1.DataSource = dataGridView1;
            chart1.DataSourceMode = DATASOURCE_SCHEME.XY;
            chart1.RefreshChart();
        }
    }
}

Results:

« Last Edit: June 12, 2016, 12:38:19 AM by CrossingCharts »