Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This code sample shows how to handle clicks in MS chart to show more info.
- // In particular here we handle the datapoint click to show the ROW of the datatable
- // corresponding to the point.
- // How To Run:
- // 1 - Create a WinForms project called WinFormTests
- // 2 - Dbl click on Form1, add a SplitContainer with Dock = Fill and Orientation = Horizontal
- // 3 - Add a MS chart to the top panel of the split container and set Dock = Fill
- // 4 - Add a DataGridView to the bottom panel of the splitContainer and set Dock = Fill
- // 5 - Open Form1.cs and copy and paste the following code
- // 6 - Build and run
- 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.Windows.Forms.DataVisualization.Charting;
- namespace WinFormTests
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- // register the hit test event
- this.chart1.MouseClick += new MouseEventHandler(chart1_MouseClick);
- // fill the data table
- DataTable dt = new DataTable();
- dt.Columns.Add("Month No.", typeof(int));
- dt.Columns.Add("Month", typeof(string));
- dt.Columns.Add("Month Description", typeof(string));
- dt.Columns.Add("Value", typeof(double));
- dt.Rows.Add("Jan", "January", 1, 10);
- dt.Rows.Add("Feb", "February", 2, 30);
- dt.Rows.Add("Mar", "March", 3, 50);
- dt.Rows.Add("Apr", "April", 4, 20);
- dt.Rows.Add("May", "May", 5, 40);
- dt.Rows.Add("Jun", "June", 6, 25);
- dt.Rows.Add("Jul", "July", 7, 35);
- dt.Rows.Add("Aug", "August", 8, 70);
- dt.Rows.Add("Sep", "September", 9, 15);
- dt.Rows.Add("Oct", "October", 10, 30);
- dt.Rows.Add("Nov", "November", 11, 5);
- dt.Rows.Add("Dec", "December", 12, 100);
- // bind the data table to chart
- this.chart1.Series.Clear();
- var series = this.chart1.Series.Add("Series 1");
- series.XValueMember = "Month No.";
- series.YValueMembers = "Value";
- series.ChartType = SeriesChartType.Line;
- this.chart1.DataSource = dt;
- this.chart1.DataBind();
- // bint the data table to datagridview
- this.dataGridView1.DataSource = dt;
- }
- void chart1_MouseClick(object sender, MouseEventArgs e)
- {
- var pos = e.Location;
- var results = chart1.HitTest(pos.X, pos.Y, false, ChartElementType.DataPoint);
- foreach (var result in results)
- {
- if (result.ChartElementType == ChartElementType.DataPoint)
- {
- var point = result.Object as DataPoint;
- var month = (int)point.XValue;
- this.dataGridView1.ClearSelection();
- foreach (DataGridViewRow row in this.dataGridView1.Rows)
- {
- if ((int)row.Cells["Month No."].Value == month)
- {
- row.Selected = true;
- break;
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement