Reputation: 23
I've been tried to connect asp.net Webform aspx.vb whith sql server,but problem is when I wrote this code Dim cn As New SqlConnection(con)
it error on con
, I try to find out why it doesn't work.
Error Message
con is not declared it may inaccessible sue to its protection level
My Web.config code
<connectionStrings>
<add name="connection"
connectionString="Data Source=HOUCHANDARA;Initial Catalog=website;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
My Module code
Imports System.Configuration
Public Module Connection
Public con As String = ConfigurationManager.ConnectionStrings("connection").ConnectionString
End Module
My aspx.vb code
Imports System.Data.SqlClient
Public Class HomePage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim cn As New SqlConnection(con)
If Not IsPostBack Then
Try
cn.Open()
MsgBox("connect")
Catch ex As Exception
MsgBox("faild")
End Try
End If
End Sub
End Class
Upvotes: 0
Views: 197
Reputation: 460138
Use
Dim cn As New SqlConnection(Connection.con)
apart from that, note that ConfigurationManager.ConnectionStrings
is also cached. So there is no performance gain in using that "global" variable. You should also use the Using
-statement for the connection to ensure that it gets disposed/closed as soon as possible even on error.
Upvotes: 3