Saturday, February 25, 2012

Data Access Error - ConnectionString property

Hi guys,

I'm getting this error:

System.InvalidOperationException: The ConnectionString property has not been initialized

when I'm trying to connect to an SQL database using the following code:

Dim mySelectQuery As String = "SELECT [tabl_id] FROM [myTable]"
Dim myConnection As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("myConnString"))
Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As SqlDataReader
myReader = myCommand.ExecuteReader()
While myReader.Read()
Response.Write(myReader("tabl_id") & "<br/>")
End While
myConnection.Close()

and in web.config:

<appSettings/>
<connectionStrings>
<add name="myConnString" connectionString="Data Source=100.100.100.100;Initial Catalog=myDatabase;User ID=me;Password=password" providerName="System.Data.SqlClient"/>
</connectionStrings>

If I place the actual connection string inside instead of trying to reference the web.config setting it works, but using 'System.Configuration.ConfigurationManager.AppSettings' returns the error. Is there something I'm doing wrong?

Ferox:

Dim myConnection As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("myConnString"))
and in web.config:

<appSettings/>
<connectionStrings>
<add name="myConnString" connectionString="Data Source=100.100.100.100;Initial Catalog=myDatabase;User ID=me;Password=password" providerName="System.Data.SqlClient"/>
</connectionStrings>

hi there,

the connection stirng element in your webconfig is actually not a child node of the appSettings but its on the same level instead. So maybe you wanna get the ConnectionStrings node instead of the AppSettings node out of the web.config.

System.Configuration.ConfigurationManager.ConnectionStrings("myConnString").ConnectionString

see if the above line works.

|||

Thanks a lot, that works perfectly! :)

No comments:

Post a Comment