SqlConnection in C #

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 an error message:

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 an error message:

The non-invoking member of 'System.Configuration.ConfigurationManager.ConnectionStrings' cannot as a method.

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

+4
source share
3 answers

Try it like this:

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

Note [] instead of () , which is used to access an array element in C #. Also note the use of the .ConnectionString property .ConnectionString , as the SqlConnection constructor expects a string.

+11
source

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

Also, use the using clause to make sure the connection is always closed and removed when you exit the 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

+6
source

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

eg.

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

So, you get access to the configuration collection as follows:

 ConfigurationManager.ConnectionStrings["conn"]; 
+2
source

All Articles