0

I have created a Line chart using MSChart 2008.I have Dates on the x axis and Double values on y axis.Now I need to find Y value on Todays Date(Which will be my x value)..Can anybody help me to achieve this.

Thanks

user2047818
  • 15
  • 1
  • 8

1 Answers1

1

I use a similar approach to this with cursors: I wanted to find the closest record to where the vertical cursor was added and show the value for that (as opposed to the value of the cursor coordinates):

If you swap out e.NewPosition with your query value (eg. today's date), the code should do what you want.

// Cursor Position Changing Event
private void chart1_CursorPositionChanged(object sender, CursorEventArgs e)
{
    //Get the nearest record and use its X value as the position
    double coercedPosition = chart1.Series[0].Points.Aggregate((x, y) => Math.Abs(x.XValue - e.NewPosition) < Math.Abs(y.XValue - e.NewPosition) ? x : y).XValue;

    //Set cursor to the coerced position
    chart1.ChartAreas[0].CursorX.Position = coercedPosition;

    SetPosition(e.Axis, coercedPosition);
}

// Update the labels with the values at the indicated position
private void SetPosition(Axis axis, double position)
{
    if (double.IsNaN(position))
        return;

    if (axis.AxisName == AxisName.X)
    {
        //Get the value at the position
        DateTime dt = DateTime.FromOADate(position);

        //set the timestamp label
        lbl_CursorTimestampValue.Text = dt.ToString();

        //get the point at that timestamp (x value)
        var point = chart1.Series[0].Points.FindByValue(position, "X");

        //set the y value label
        lbl_CursorYValue.Text = point.IsEmpty == true ? "--" : point.YValues[0].ToString();
    }
}

Also note that if you will want to convert your DateTime to an OA value:

double yourOADate = yourDateTime.ToOADate();
Josh Lyon
  • 399
  • 5
  • 11