I'm writing a code in C#.Net WinForms to add label on clicking some datapoints on chart. Before clicking the chart, the graph looks like this.
Now I click a datapoint between 330-340. The chart shows selected datapoint with double label (338.61). As shown below:
Here is the below code for chart_mouseclick
private void chart1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
double mouse_Xvalue = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X);
double mouse_Yvalue = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Y);
DataPoint Prev_DataPoint = chart1.Series[0].Points.Select(x => x)
.Where(x => x.XValue >= mouse_Xvalue)
.DefaultIfEmpty(chart1.Series[0].Points.First()).First();
DataPoint Next_DataPoint = chart1.Series[0].Points.Select(x => x)
.Where(x => x.XValue <= mouse_Xvalue)
.DefaultIfEmpty(chart1.Series[0].Points.Last()).Last();
DataPoint Add_DataPoint = Math.Abs(Prev_DataPoint.XValue - mouse_Xvalue) < Math.Abs(Next_DataPoint.XValue - mouse_Xvalue) ? Prev_DataPoint : Next_DataPoint;
int add_data_point_index = chart1.Series[0].Points.IndexOf(Add_DataPoint);
DataPoint max = Add_DataPoint;
for (int i = add_data_point_index - 10; i <= add_data_point_index + 10; i++)
{
DataPoint dp = chart1.Series[0].Points[i];
if (dp.YValues[0] > max.YValues[0])
{
add_data_point_index = i;
max = dp;
}
}
chart1.Series[1].Points.Add(max);
chart1.Series[1].Sort(PointSortOrder.Ascending, "X");
for (int i = 0; i < chart1.Series[1].Points.Count; i++)
{
chart1.Series[1].Points[i].Label =
Math.Round(chart1.Series[1].Points[i].XValue, 2).ToString();
}
}
}
What is wrong with the code ?