Link to home
Start Free TrialLog in
Avatar of AlexPonnath
AlexPonnathFlag for United States of America

asked on

Problem with Database connection

Hi, i need some pointers and help how to code the folowing

i have a Form which has a couple of fields which represent Servername, userid and Password as well as a
Bttn on the form which opens a connection based on the data provided. I enclosed the code below..

My problem is that i am able to open the connection just fine but as soon as i try to access the connection
from a diffrent part of code in form i have no luck. So my question is where and how do i declare the connection so it
can be opened via my bttn but then accessed by other code outside the click event.

thanks

Private Sub bttnConnectDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnConnectDB.Click
        If Me.txtServerName.TextLength <> 0 Then
            If Me.txtUserName.TextLength <> 0 Then

                myconnectionString = "Data Source=" & Trim(txtServerName.Text) & ";Persist Security Info=True;User ID=" & Trim(txtUserName.Text)

                Dim result As Boolean = False

                Dim connection As New SqlConnection(myconnectionString)
                Try
                    connection.Open()
                    result = True
                    Me.lblServerVersion.Text = connection.ServerVersion
                Catch exSQL As SqlException
                    'ErrorList.Add(exSQL)
                    result = False
                Catch ex As Exception
                    'ErrorList.Add(ex)
                    result = False

                    'Finally
                    '   connection.Close()

                    'connection.Dispose()
                End Try


            Else
                MsgBox("Please enter a valid User Name for the Database server", MsgBoxStyle.Exclamation, "Error...")
            End If


        Else
            MsgBox("Please enter a valid address or name for the Database server", MsgBoxStyle.Exclamation, "Error...")
        End If

        MsgBox(myconnectionString)


    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial