I am trying to click on my pie chart that i drug in from the toolbox in Windows form for C# and show detailed info from that slice. Right now this is the code I have for the click. I'm wondering if this is the correct route or what route I should be taking.
private void chart1_Click(object sender, EventArgs e)
{
HitTestResult results = chart1.HitTest((e as MouseEventArgs).X, (e as MouseEventArgs).Y);
}
I am also using System.Windows.Forms.DataVisualization.Charting;
Yes, that is the correct appoach.
You now can test if the DataPoint
is valid etc..
I would use the MouseClick
btw, which has MouseEventArgs
by default.
You can even code the MouseMove
event and use the same hittest to control a cursor to show that the user is over a datapoint..
Here is an example:
private void chart1_MouseClick(object sender, MouseEventArgs e)
{
HitTestResult hit = chart1.HitTest(e.X, e.Y, ChartElementType.DataPoint);
if (hit.PointIndex >= 0 && hit.Series != null)
{
DataPoint dp = chart1.Series[0].Points[hit.PointIndex];
label1.Text = "Value #" + hit.PointIndex + " = " + dp.XValue;
}
else label1.Text = "";
}
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
HitTestResult hit = chart1.HitTest(e.X, e.Y);
var dp = hit.Object as DataPoint;
Cursor = (dp is null) ? Cursors.Default : Cursors.Hand;
}
Note the the two events use different ways to test for a hit..!
I love the accepted answer. But here is a slightly different approach that uses common code do the hit-testing, and also supports hovering and clicking on the items in the legend.
private int pieHitPointIndex(Chart pie, MouseEventArgs e)
{
HitTestResult hitPiece = pie.HitTest(e.X, e.Y, ChartElementType.DataPoint);
HitTestResult hitLegend = pie.HitTest(e.X, e.Y, ChartElementType.LegendItem);
int pointIndex = -1;
if (hitPiece.Series != null) pointIndex = hitPiece.PointIndex;
if (hitLegend.Series != null) pointIndex = hitLegend.PointIndex;
return pointIndex;
}
private void pie_MouseClick(object sender, MouseEventArgs e)
{
Chart pie = (Chart)sender;
int pointIndex = pieHitPointIndex(pie, e);
if (pointIndex >= 0)
{
DataPoint dp = pie.Series[0].Points[pointIndex];
// do what you want to do with a click
}
}
private void pie_MouseMove(object sender, MouseEventArgs e)
{
Chart pie = (Chart)sender;
int pointIndex = pieHitPointIndex(pie, e);
if (pointIndex >= 0)
{
Cursor = Cursors.Hand;
}
else
{
Cursor = Cursors.Default;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With