1

Hello i am trying to add a click event to chart points but i am getting the following Error when i click the chart "Object reference not set to an instance of an object"

here is my code

Private Sub Chart1_Click(sender As Object, e As System.EventArgs) Handles Chart1.Click
    Try
        Dim pointindex As Integer
        If result.ChartElementType = ChartElementType.DataPoint Then
            pointindex = result.PointIndex
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub Form1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
    result = Chart1.HitTest(e.X, e.Y)
End Sub
FPGA
  • 3,525
  • 10
  • 44
  • 73
  • My guess is that the form does not receive the mouse down event so result is not set leading to the error mentioned. This is something you can easily check with a breakpoint or debug output. If that really is the problem you can use `Cursor.Position` in `Chart1_Click`. – Paul B. Jul 16 '12 at 06:58
  • Great. I'll post a more descriptive answer for future reference. – Paul B. Jul 16 '12 at 14:33

1 Answers1

1

If the mouse cursor is above a control only the control will receive events but not the form (for workarounds see e.g. this question: Winforms : Intercepting Mouse Event on Main Form first, not on Controls).

So Form1_MouseDown will not fire and result will still be Nothing in Chart1_Click.

A workaround could look like this:

Private Sub Chart1_Click(sender As Object, e As System.EventArgs) Handles Chart1.Click
    Try
        Dim pointindex As Integer
        Dim result As HitTestResult
        result = Chart1.HitTest(Cursor.Position.X, Cursor.Position.Y)
        If result.ChartElementType = ChartElementType.DataPoint Then
            pointindex = result.PointIndex
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
Community
  • 1
  • 1
Paul B.
  • 2,394
  • 27
  • 47