Question

I'm writing a web tool using asp.net and VB. I've been instructed by my client to use the web.config file to hold the database connection string (instead of using a global variable, which I've been doing up to now).

Most of the online help for this agrees on how to do this, with minor differences. The web.config file:

<configuration>
  <connectionStrings>
     <add name="MyConn"
         connectionString="Provider=SQLOLEDB;Data Source=MyServer;
             Initial Catalog=DBName;Persist Security Info=True;User ID=MyUser;
             Password=MyPass"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

And in my code-behind page:

Imports System.Configuration
Dim conn as String

conn = 
ConfigurationManager.ConnectionStrings["MyConn"].ConnectionStrings

The forums I've looked at agree that this should work in vb or C#. But in my code-behind, I'm getting the error "Value of type 'System.Configuration.ConnectionStringSettingsCollection' cannot be converted to 'String'." If I change the connection string to an object:

Dim conn as object

Then the error goes away, but I don't think that's solving the problem. Can anyone tell me why the above code won't render the string in my web.config file? According to multiple forums, this ought to work.

Thanks for any help.

EDIT:

I did try ending the line with 'ConnectionString' (final 's' removed), which is in the online help - same result. I left the final 's' in my code because the Microsoft 'Intellesense' thing puts it in there, but it gives me the same result either way.

FURTHER EDIT:

When I changed the conn to a 'Object' type, my code tells me 'Identifier Expected' where the ["MyConn"] is. There does seem to be something wrong, even though several online resources tell me this is correct.

Thanks again.

Was it helpful?

Solution

conn = 
ConfigurationManager.ConnectionStrings["MyConn"].ConnectionStrings

Must be (pay attention to the VB.NET style)

conn = 
ConfigurationManager.ConnectionStrings("MyConn").ConnectionString

And that returns a string.

OTHER TIPS

Previous refers,
But I find the following necessary at the top of the page

Imports System.Data  
Imports System.Data.SqlClient

Also the inclusion of '.ToString'

Dim conn As String = ConfigurationManager.ConnectionStrings("MyConn").ConnectionString.ToString
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top