[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 186
  • Last Modified:

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.


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)
                    result = True
                    Me.lblServerVersion.Text = connection.ServerVersion
                Catch exSQL As SqlException
                    result = False
                Catch ex As Exception
                    result = False

                    '   connection.Close()

                End Try

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

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


    End Sub

Open in new window

1 Solution
Fernando SotoCommented:
Hi AlexPonnath;

Define this at class level, outside of any function/method/Sub/Event handler.

Private connection As SqlConnection

Then replace this line in the event handler:

Dim connection As New SqlConnection(myconnectionString)

With this:

connection = New SqlConnection(myconnectionString)

The problem is that you are defining the connection inside of a function and will not be available to other methods.


Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now