2012-07-16 79 views
1

你好,我是想添加一個click事件圖表點,但我得到以下錯誤,當我點擊圖表「對象引用不設置到對象的實例」vb.net圖表控制點onclick事件

這裏是我的代碼

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 
+0

我的猜測是,形式不接收鼠標按下事件,因此結果將不設置導致提到的錯誤。這可以通過斷點或調試輸出輕鬆進行檢查。如果真的是這個問題,你可以在'Chart1_Click'中使用'Cursor.Position'。 – 2012-07-16 06:58:42

+0

那工作,謝謝:) – FPGA 2012-07-16 13:50:49

+0

太好了。我將發佈一個更具描述性的答案以供將來參考。 – 2012-07-16 14:33:55

回答

1

如果將鼠標光標是控制上面只控制將接收事件,但不是形式(見的解決方法例如這樣的問題:Winforms : Intercepting Mouse Event on Main Form first, not on Controls)。

因此Form1_MouseDown不會觸發,result仍然會在Chart1_ClickNothing

一種解決方法看起來是這樣的:

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