Hi there, im new to VB and am trying to work out how i can check that my database connection info is correct before i connect.

error example with incorrect info: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

My code:

Public Sub SQL_Connect()
ConStr = "data source=" & DB_Server & "; initial catalog=" & DB_Name & ";" + _
"User ID=" & DB_User & "; pwd=" & DB_Pass & "; Integrated Security=SSPI"
End Sub

Private Sub B_Go_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles B_Go.Click

DB_Server = TB_S.Text
DB_Name = TB_D.Text
DB_User = TB_U.Text
DB_Pass = TB_P.Text

If DB_Server = "" Or DB_Name = "" Or DB_User = "" Or DB_Pass = "" Then
MessageBox.Show("You must fill out all fields", "ERROR")
ElseIf B_Go.Text = "CONNECT" Then

SQL_Connect()

Timer.Enabled = True
TypeComboBox()
EmpComboBox()
CONNECT_Enabled()
B_Go.Text = "DISCONNECT"
Else
B_Go.Text = "CONNECT"
DISCONNECT_Enabled()
Timer.Enabled = False
End If
End Sub

You should use the add datasource menu option. With this you can test your connection.

can i not do it with code i didnt want to use a menu option?

winTA,

Please verify whether an SQL server instance is running or installed or not.

To do so,
1. Open Server Explorer from view Menu.
2. Right Click on data connection + Add DataConnection
3. Chage - Microsoft SQL Server (SqlClient)
4. Type - servername,password, username
5. Select database.

Second, its difficult to read the code you posted. It is not posted here with bb code tags. So wrap up source code in bb code tags. See # icon at toolbar.

I have done what i wanted:

SQL_Connect()
Dim sqlConn As New System.Data.SqlClient.SqlConnection(ConStr)
Try
sqlConn.Open()
Catch ex As Exception
MessageBox.Show("Connection Refused.", "ERROR")
Return
End Try

This article has been dead for over six months. Start a new discussion instead.