4

In VB.NET I can use:

Protected Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Active").ConnectionString)

However, when I do the following in C#:

protected SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings("conn"));

I get the error:

The name 'ConfigurationManager' does not exist in the current context

Then if I change it to:

protected SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("conn"));

I get the error:

Non-invocable member 'System.Configuration.ConfigurationManager.ConnectionStrings' cannot be used like a method.

Why is this and how can I connect to my SQL Server database using C#?

3 Answers 3

11

Try like this:

protected SqlConnection conn = new SqlConnection(
    ConfigurationManager.ConnectionStrings["conn"].ConnectionString
);

Notice the [] instead of () which is what is used to access an element of an array in C#. Also notice the usage of the .ConnectionString property call as the SqlConnection constructor expects a string.

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

4 Comments

I'm still getting The name 'ConfigurationManager' does not exist in the current context. But I've added System.Configuration to my References
@Curt - try adding "using System.Configuration;" at the top. And remember to also use the using statement as Ofer Zelig suggests.
@Curt, make sure you have referenced the System.Configuration assembly to your project and that you have added a using System.Configuration in order to bring the ConfigurationManager class insto scope.
I definetely have referenced it and I've used using System.Configuration too... very confused
8

Change the last pair of parentheses to square brackets. In C#, parentheses are used in method calls, whether square brackets are used to access members inside a collection (or so).

In addition, use the using clause to ensure that the connection is always closed and disposed when you go out of scope:

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn"]))
{
...
}

Read about it here: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx

Comments

2

In C#, you read collections using square bracket syntax:

e.g.

string[] strings = new[] { "first", "second", "third" };

string secondString = strings[1];

So you access the Configuration collection like this:

ConfigurationManager.ConnectionStrings["conn"];

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.