Hi, I'm new in VB.NET and I'm having trouble with creating a public sqlconnection in a VB Module.
I have declared conn as public sqlconnection but when I use it to the other forms its value is equal to "nothing". I hope you can enlighten me here. thanks in advance.

This is my Module:

Imports System
Imports System.Data
Imports System.Data.SqlClient

Module modSindBad

#Region "Variables"

    Public con As String
    Public conn As SqlConnection
    Public cmd As SqlCommand
    Public da As SqlDataAdapter
    Public dt As DataTable
    Public ds As DataSet

#End Region

    Public Sub ServerConnection()

        Try

            con = "Data Source=SAMI-HP\SQLSERVER;Initial Catalog=SINDBAD;User ID=sa;Password=Administrator@123"
            Dim conn = New SqlConnection(con)
            conn.Open()

            If conn.State = ConnectionState.Open Then
                MsgBox("conn open")
            End If

        Catch

            MsgBox("Unexpected Error Occured!" & vbNewLine & "Error Code: " & Err.Number & "Error Description: " & Err.Description & _
                   "Error Source: " & Err.Source, vbExclamation, "Error Handler")

        End Try

    End Sub

End Module

And this is my form:

Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class mdBank

    Dim dt As DataTable

#Region "Form Load"

    Private Sub mdBank_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ServerConnection()

        ReadmdBankInfo()

    End Sub

#End Region

#Region "Database Commands"

    Private Sub ReadmdBankInfo()

        Dim cmd = New SqlCommand
        cmd.Connection = conn ''Value = nothing
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SELECT * FROM mdBank"

        Dim dt = New DataTable
        Dim da = New SqlDataAdapter
        da.SelectCommand = cmd
        da.Fill(dt)

        Me.dgvBank.DataSource = dt
        Me.dgvBank.Refresh()

    End Sub

#End Region


End Class

Edited 3 Years Ago by romz

May be your declaring again in ServerConnection() as Dim conn = New SqlConnection(con)
in top also there is a variable with scope public and here its local to that module.

Your right pgmer, should have not dim conn as local again "Dim conn = New SqlConnection(con)". It should be "conn = new sqlconnection(con)" only.

Thanks alot.

This question has already been answered. Start a new discussion instead.