Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pie chart slice click

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;

like image 476
ebraun99 Avatar asked Dec 23 '22 20:12

ebraun99


2 Answers

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..!

enter image description here

like image 166
TaW Avatar answered Dec 28 '22 07:12

TaW


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;
    }
}
like image 28
Jeff Roe Avatar answered Dec 28 '22 05:12

Jeff Roe