MS Chart, How to get CursorX data point in the mouse move event?

1.7k Views Asked by At

I have a question regarding the ms chart: how do I get the CursorX data point in the mouse move event?

1

There are 1 best solutions below

0
On

Assuming that your chart is called _chart and that the index of the chart you're after is CHART_INDEX:

Firstly, calculate the X-Axis coord from from the X pixel coord:

// Assume MouseEventArgs e is passed in from (for example) chart_MouseDown():
var xAxis = _chart.ChartAreas[CHART_INDEX].AxisX;
double x = xAxis.PixelPositionToValue(e.Location.X);

Now x is the X coord (in X axis units) of the pixel on the X axis.

Then you have to determine the nearest preceeding data point from the X axis value.

Assuming that SERIES_INDEX is the index of the series you're interested in:

private double nearestPreceedingValue(double xCoord)
{
    // Find the last  at or before the current xCoord.
    // Since the data is ordered on X, we can binary search for it.

    var data  = _chart.Series[SERIES_INDEX].Points;
    int index = data.BinarySearch(xCoord, (xVal, point) => Math.Sign(xCoord - point.XValue));

    if (index < 0)
    {
        index = ~index;               // BinarySearch() returns the index of the next element LARGER than the target.
        index = Math.Max(0, index-1); // We want the value of the previous element, so we must decrement the returned index.
    }                                 // If this is before the start of the graph, use the first valid data point.

    // Return -1 if not found, or the value of the nearest preceeding point if found.
    // (Substitute an appropriate value for -1 if you need a different "invalid" value.)

    return (index < data.Count) ? (int)data[index].YValues[0] : -1;
}