SQL Connection: Connecting to Multiple Databases - Code
(Page 3 of 4 )
The code for connecting to one or the other database is through the selection of a database item in the dropdownlist. Presently there are only two servers configured for connection. The code for connecting to the databases is shown as follows:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As
System.EventArgs) _
Handles Button2.Click
If DropDownList1.SelectedItem.ToString Is "books" Then
Dim dynSQL As New SqlClient.SqlConnection
dynSQL.ConnectionString = ConfigurationSettings.AppSettings("books") Try
dynSQL.Open()
TextBox1.Text = dynSQL.ConnectionString
If dynSQL.State = 1 Then
Label1.Text = "Server State is Open"
Else
Label1.Text = "Server State is Closed"
End If
Catch ex As SqlClient.SqlException
TextBox1.Text = ex.Message
End Try
dynSQL.Close()
ElseIf DropDownList1.SelectedItem.ToString Is "info" Then
Dim dynSQL2 As New SqlClient.SqlConnection
dynSQL2.ConnectionString =
ConfigurationSettings.AppSettings("info") Try
dynSQL2.Open()
TextBox1.Text = dynSQL2.ConnectionString
If dynSQL2.State = 1 Then
Label1.Text = "Server State is Open"
Else
Label1.Text = "Server State is Closed"
End If
Catch ex As SqlClient.SqlException
TextBox1.Text = ex.Message
End Try
dynSQL2.Close()
End If
End Sub
Results
The next two pictures shows the result of trying to connect to the databases.


However, if the servers are disconnected, or are not accessible, the SQL exception is captured and displayed in the text box as shown below.

Next: Connection Using Dynamic Properties of the SQLConnection Control >>
More MS SQL Server Articles
More By Jayaram Krishnaswamy