Search code examples
c#datetimechartspositionpixel

How to get Pixel Position from DateTime Value on X-Axis?


I'm trying to retrieve the pixel position on the chart of a DataPoint using its X Value (DateTime). I'm using this code after the Chart has been painted but I get a very large number:

DateTime date = ... ; // DateTime of the DataPoint, I verified the date is correct and the chart contains it.    
var pixelsPosition = ChartAreas[0].AxisX.ValueToPixelPosition(date.ToOADate()); 
// Here pixelsPosition is a very large number, above 600 000.

These are the Chart settings:

Series[0].XValueType = ChartValueType.DateTime;
Series[0].IsXValueIndexed = true;

The Chart has around 2000 Points.

I'm using the same code to retrieve a pixel position of a DataPoint using the Y Value and it works. I'm sure it's a stupid problem but I can't figure it out.

Working code for the Y-Axis

double yValue = 100;
double pixPositionY = ChartAreas[0].AxisY.ValueToPixelPosition(yValue); // THIS WORKS

What am I doing wrong?

EDIT: I read that the method ValueToPixelPosition works only on Paint Events, I've tried to execute it on the Paint and PrePaint events but I get the same error.


Solution

  • I have found the solution to my problem:

    DateTime date;
    int pixelPositionX = 0;
    var point = Series[0].Points.Where(X => X.XValue == date.ToOADate()).FirstOrDefault();
    var index = (point != null) ? Series[0].Points.IndexOf(point) : -1;
    
    if (index > -1)
        pixelPositionX  = (int)ChartAreas[0].AxisX.ValueToPixelPosition(index + 1);
    

    That gives me the correct position of the DataPoint on the screen. ValueToPixelPosition works if I pass the dataPoint index as parameter rather than the datetime value converted to OADate. I'm not sure if this is the right solution but it's working for me.