Reputation: 838
I want to know how to check if my program is connected to database or not.
here is my code::
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
conn.Open()
If conn.State = ConnectionState.Open Then
MsgBox("YOU ARE CONNECTED TO THE DATABASE")
Else
MsgBox("YOU ARE NOT CONNECTED TO THE DATABASE, CONTACT YOUR ADMINISTRATOR")
End If
conn.Close()
End Sub
this code works fine if the connection string is correct, the message says open; but when the connection is wrong it ends up in error the error is:
Login failed for user
Here is the Algorithm of what I want to happen:
If thisProgram is connected then
Messagebox ("YOU ARE CONNECTED TO THE DATABASE")
Else
MessageBox ("YOU ARE NOT CONNECTED TO THE DATABASE, CONTACT YOUR ADMINISTRATOR")
End If
Please help thank you
Upvotes: 0
Views: 309
Reputation: 1365
Simple, you could just put try and catch.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
conn.Open()
If conn.State = ConnectionState.Open Then
MsgBox("open")
Else
MsgBox("no")
End If
conn.Close()
Catch
MsgBox("no")
End Try
End Sub
Upvotes: 1