9

In my code behind page, how do I access the connection string which is stored in my web.config file?

3 Answers 3

22
System.Web.Configuration.WebConfigurationManager.ConnectionStrings["YouConnStringName"].ConnectionString;

This requires references to System.Configuration.dll and System.Web.dll.

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

3 Comments

Shouldn't this be System.Web.Configuration.WebConfigurationManager.ConnectionStrings...
This gives me an error: Cannot apply indexing with [] to an expression of type 'System.Configuration.ConnectionStringSettingsCollection' Any ideas how to fix that?
Not sure exactly, but my guess would be you are not using System.Web.Configuration.WebConfigurationManager.ConnectionStrings["conString"].ConnectionString; or maybe a stretch is you need to reference system.configuration? You get that error because the collection you are using doesn't implement IList and probably only implements IEnumerable.
4

How to: Read Connection Strings from the Web.config File

Comments

1

From comment on http://msdn.microsoft.com/en-us/library/ms178411.aspx

string c = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["myconnectionstringname"].ConnectionString;

Requires your project to reference to System.Web and System.Configuration. I had to actually add a reference to "System.Configuration" not just add a Using.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.