MS Chart cursor position not linked to X data

Nathan Smith 1 Reputation point
2021-04-05T17:09:33.407+00:00

I have an MS chart that is showing logarithmic frequency data in my c# app. I want to use a cursor to select a data point. Since the cursor doesn't automatically snap to the closest data point, I had to write a routine that would do that for me.

private void chart_CursorPositionChanged(object sender, CursorEventArgs e)
        {
            if (double.IsNaN(e.NewPosition)) return;

            if (chart.ChartAreas[0].CursorX.IsUserEnabled)
            {
                double coercedPosition = chart.Series[0].Points.Aggregate((x, y) => Math.Abs(x.XValue - e.NewPosition) < Math.Abs(y.XValue - e.NewPosition) ? x : y).XValue;
                //move the cursor to the closest point
                chart.ChartAreas[0].CursorX.Position = coercedPosition;
                txtZPrime.Text = SelectedStep.GetZatFreq(coercedPosition).ToString();
            }
        }

The problem is, when the cursor is moved, and I get the position of the cursor, the position is not the position of the cursor in the X data line. Instead, it's the number of major divisions from the left of the chart.

I made sure the data is charting correctly and the labels are correct for the X axis, but the cursor position is not correlated to the X data.

Any ideas what's the problem?

Thanks

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,837 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,302 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-04-06T02:22:14.807+00:00

    Hi NathanSmith-2125,
    Please try to use Axis.PixelPositionToValue(Double) method to convert an absolute pixel position along an axis to an axis value.

    chart.ChartAreas[0].CursorX.Position =chart.ChartAreas[0].AxisX.PixelPositionToValue(coercedPosition);  
    

    And note that this method only works in paint events.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.