次の方法で共有


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_Load イベント ハンドラーは、新しい Connection オブジェクトを connEvent に割り当て、その後、接続を開くことで、オブジェクトを実際に作成します。 もちろん、実際のアプリケーションでは、Form_Load イベント ハンドラーで、ここに示されている処理よりも多くの処理が実行されます。