0

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 
5
  • 1
    Include the error message that you get on con. Commented Feb 11, 2015 at 15:11
  • Once you figure out how to open your connection you need to add a FINALLY block in your code to close and destroy the connection object so it releases the connection back to the pool. Commented Feb 11, 2015 at 15:12
  • And the error is? Catching an exception without showing the error message is a bit useless. Also, remember that when you run this code in the IIS context, the current user is the one used to start the IIS service. It need to have permissions to open Sql Server Commented Feb 11, 2015 at 15:12
  • 'con' is not declared it may inaccessible sue to its protection level Commented Feb 11, 2015 at 15:13
  • 1
    I'm no VB expert but shouldn't it be Dim cn As New SqlConnection(Connection.con) Commented Feb 11, 2015 at 15:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.