see values of chart points when the mouse is on points

Asma Good picture Asma Good · May 18, 2012 · Viewed 52.4k times · Source

I have a chart and I want the user to see the values when the pointer is on the points. By using digEmAll's help in the page finding the value of the points in a chart ,I could write the following code:

Point? prevPosition = null; 
ToolTip tooltip = new ToolTip();  

void chart1_MouseMove(object sender, MouseEventArgs e) 
{     
    var pos = e.Location;     
    if (prevPosition.HasValue && pos == prevPosition.Value)         
        return;     
    tooltip.RemoveAll();     
    prevPosition = pos;     
    var results = chart1.HitTest(pos.X, pos.Y, false, ChartElementType.PlottingArea);     
    foreach (var result in results)     
    {         
        if (result.ChartElementType == ChartElementType.PlottingArea)         
        {            
            chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";          
        }    
    } 
} 

by the above code,the user can see the values when the pointer is near to a series.But now How can I let the user to see the values only when the pointer is on the points? I replaced

int k = result.PointIndex;
if (k >= 0)
{
    chart1.Series[0].Points[k].ToolTip = "X=#VALX, Y=#VALY";
}

instead of

chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";

to solve my problem.But It wasn't usefull.

Answer

digEmAll picture digEmAll · May 18, 2012

You should modify the code in this way:

Point? prevPosition = null;
ToolTip tooltip = new ToolTip();

void chart1_MouseMove(object sender, MouseEventArgs e)
{
    var pos = e.Location;
    if (prevPosition.HasValue && pos == prevPosition.Value)
        return;
    tooltip.RemoveAll();
    prevPosition = pos;
    var results = chart1.HitTest(pos.X, pos.Y, false,
                                    ChartElementType.DataPoint);
    foreach (var result in results)
    {
        if (result.ChartElementType == ChartElementType.DataPoint)
        {
            var prop = result.Object as DataPoint;
            if (prop != null)
            {
                var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
                var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);

                // check if the cursor is really close to the point (2 pixels around the point)
                if (Math.Abs(pos.X - pointXPixel) < 2 &&
                    Math.Abs(pos.Y - pointYPixel) < 2)
                {
                    tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
                                    pos.X, pos.Y - 15);
                }
            }
        }
    }
}

The idea is to check if the mouse is very close to the point e.g. 2 pixels around it (because is really unlikely to be exactly on the point) and show the tooltip in that case.

Here's a complete working example.