共用方式為


ADO 事件具現化:Visual Basic

若要在 Visual Basic 中處理 ADO 事件,您必須使用 WithEvents 關鍵字宣告模組層級變數。 變數只能宣告為類別模組的一部分,而且必須在模組層級宣告。 不過,這並沒有看起來那麼嚴格,因為 Visual Basic Form 物件也是類別。 處理 ADO 事件最簡單的方式是使用 WithEvents 宣告變數。 下列範例會處理 Connection 物件的 ConnectComplete 事件:

' BeginEventExampleVB02  
Dim WithEvents connEvent As Connection  
Attribute connEvent.VB_VarHelpID = -1  
  
Private Sub Form_Load()  
Dim strConn As String  
  
   ' Create a new object with event  
   ' handling enabled.  
   strConn = "Provider=sqloledb;" & _  
      "Data Source=MyServer;" & _  
      "Initial Catalog=Northwind;" & _  
      "Integrated Security=SSPI;"  
   Set connEvent = New ADODB.Connection  
   connEvent.Open strConn  
End Sub  
  
Private Sub connEvent_ConnectComplete(ByVal pError As ADODB.Error, _  
    adStatus As ADODB.EventStatusEnum, _  
    ByVal pConnection As ADODB.Connection)  
Dim strMsg As String  
  
   If adStatus = adStatusErrorsOccurred Then  
      Select Case pError.Number  
         Case adErrOperationCancelled  
            ' The operation was cancelled in the  
            ' Will event. Notify the user and exit.  
            strMsg = "I'm sorry you can't connect right now." & vbCrLf  
            strMsg = strMsg & "Click OK to exit."  
            Unload Me  
         Case Else  
            strMsg = "Error " & Format(pError.Number) & vbCrLf  
            strMsg = strMsg & pError.Description  
            strMsg = strMsg & "Click OK to exit."  
            Unload Me  
      End Select  
   End If  
   frmWait.btnOK.Enabled = True  
End Sub  
' EndEventExampleVB02  

Connection 物件是使用 WithEvents 關鍵字在 Form 層級宣告,以啟用事件處理。 Form_Load 事件處理常式實際上會藉由將新的 Connection 物件指派給 connEvent 來建立物件,然後開啟連接。 當然,實際應用程式會在 Form_Load 事件處理常式中執行更多處理,而非僅限於此處所展示。