Search code examples
c#winformszedgraph

ZedGraph: Check which data point is clicked on line graph?


I am working on a windows form app with a zedgraph and a datagridview. The datagridview has a row for every point in the line graph, and when the user clicks on a point in the graph I want it to highlight the equivalent row in the datagridview.

So how can I find out which point the user has clicked? (I don't need any code for datagridview part).


Solution

  • I figured it out. You can use GraphPane.FindNearestObject to find the point that was clicked.

    It seems that nearestObject is null if you do not click a point and is of type LineItem if you do, and then index will tell you which point was clicked.

    private void zedGraphControl_MouseClick(object sender, MouseEventArgs e)
    {
        object nearestObject;
        int index;
        this.zedGraphControl.GraphPane.FindNearestObject(new PointF(e.X, e.Y), this.CreateGraphics(), out nearestObject, out index);
        if (nearestObject != null && nearestObject.GetType() == typeof(LineItem))
        {
            // 'index' is the index of that data point
            dataGridView.CurrentCell = dataGridView.Rows[index].Cells[0];
        }
    }