I would like to get the Y Value for a series corresponding to the X position of a ChartArea that the user has clicked-upon.
I have tried to capture the X position of the mouse within the chartarea that is clicked upon but I am getting NaN returned for the result:
private void chart_Click(object sender, EventArgs e)
{
double XVal = chart.ChartAreas[0].CursorX.Position;
}
Once I have got the X position in the chartarea where the user has clicked the mouse, I would then like to use that to get the Y value of a series at that x-position.
As for
chart.ChartAreas[0].CursorX
: AChart Cursor
is an object created by and used for zooming and which thenSo it has not much to do with the mouse cursor and is not valid when not zooming or (when zooming is disabled) for selecting.
There are a few options you have; unfortunately none are both simple and exactly what you asked for.
One simple thing is to use the
HitTest
forCharts
:This is simple and safe but will work only when the cursor is actually over a
DataPoint
. How well it suits you may depend on theChartType
; Very well forColumns
orBars
but not so well forPoints
orBubbles
..And you could call
PixelPositionToValue
:In theory this is only safe to call from one of the
Paint
events but in practice it seems to work fine when called from user interactions as well. (If you run into problems you could do a dummy call on one of thePaint
events and abort it with a flag after pulling the value(s) you want; the example does a lot more than what you need, but I doubt it will be necessary at all..)However it will only bring back the
Values
according to the axis, not the nearestDataPoint
. If you really need to get at the actualDataPoint
you would then have to do a search over thePoints
of yourSeries
..:This should bring up the previous and next
DataPoint
. It is up to you to decide which one to use..You'll need a MouseClick-Handler for your chart control instead of a normal Click-Handler, because of the "MouseEventArgs":
First convert the mouse click position to a relative position:
Then convert relative position to axis position:
Then use the axis position to probe the series (eg interpolate or nearest point as you like)