2014-03-01 100 views
1

我正在開發銷售點系統。我想顯示用戶的數據庫連接狀態。我使用MS Access 2013數據庫和Visual Studio 2010(VB)。我創建的模塊爲這個項目如下,如何在VB 2010中顯示數據庫連接狀態

Imports System.Data.OleDb 
Module ModConVar 
    Public sql As String 
    Public cmd As OleDbCommand 
    Public dr As OleDbDataReader 

    Public conn As OleDbConnection 
    Public connStr As String = System.Environment.CurrentDirectory.ToString & "\NCS_POS_DB.accdb" 

    Public Sub ConnDB() 
     Try 
      conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & connStr & "") 
      conn.Open() 
     Catch ex As Exception 
      MsgBox(ex.Message) 
     End Try 
    End Sub 
End Module 

和我有一個在主MDI形式命名lblDBStatus標籤,我試圖與跟隨着的代碼,但它dosent工作。

If conn.State = ConnectionState.Open Then 
    lblDBStatus.Text = "CONECTED" 
End If 

有什麼建議嗎?

+0

你說的「不工作」是什麼意思?你什麼時候運行第二個代碼塊?康恩的價值及其預期狀態如何? – Markus

+0

它不工作..顯示一個錯誤:(我認爲「conn.State = ConnectionState.Open」是錯誤的語法。 – Geeth

回答

0

只有當連接狀態打開時,您纔會顯示「CONNECTED」。否則,你的標籤就不會顯示任何

試試這個,並確保連接的開放:

If conn.State = ConnectionState.Open Then 
    lblDBStatus.Text = "CONNECTED" 
Else 
    lblDBStatus.Text = "DISCONNECTED" 
End If 
0

OleDbConnection暴露了StateChanged事件。

所以,你可以跟蹤這樣的狀態:

Public Sub ConnDB() 

    Using connection As New OleDbConnection("...") 
     AddHandler connection.StateChange, AddressOf Me.OnConnectionStateChange 
     Try 
      connection.Open() 
      'Do stuff.. 
     Catch ex As Exception 
      Throw ex 
     Finally 
      RemoveHandler connection.StateChange, AddressOf Me.OnConnectionStateChange 
     End Try 
    End Using 

End Sub 

Private Sub OnConnectionStateChange(sender As Object, e As StateChangeEventArgs) 
    MessageBox.Show(e.CurrentState.ToString()) 
End Sub 
+0

請清楚解釋清楚.. :( – Geeth

+0

@Geeth請清楚解釋什麼不清楚。 –