Abe Miessler
Abe Miessler

Reputation: 85126

Short hand for getting connection string from config file?

I was creating a SQL Connection and when I got to the point:

SqlCommand cmd = new SqlCommand("test",

intellisense prompted me with connection:. I tried finishing it with:

SqlCommand cmd = new SqlCommand("test", connection:ConnStringName);

but this erorrs out. Is there a short hand way for me to get a connection string from my config file? I seem to remember doing this before but I think it was on the .aspx file and not the .cs file.

Upvotes: 1

Views: 284

Answers (4)

marc_s
marc_s

Reputation: 755531

What you're seeing is Visual Studio presenting you with a named parameter.

When you look at the SqlCommand class, it has several constructors - e.g. this one here:

public SqlCommand(
    string cmdText,
    SqlConnection connection,
    SqlTransaction transaction
)

So with the named parameters of .NET 4, you could imagine calling this constructor with:

SqlCommand cmd = new SqlCommand("...", connection:AValidSqlConnectionHere)

but you'd have to provide a value of type SqlConnection for the connection parameter. This is not a shortcut for loading a configuration setting or something - it's just the intellisense for named parameters...

Right now, the SqlCommand class has a whole series of overloaded constructors, to cope with the different scenarios of providing more or less parameter values. With .NET 4.0 and the named and optional parameters, you could create just a single constructor (or any other method) and provide defaults for some parameters, and allow the user to call your method (or constructor) with named parameters to provide exactly the information he has available for the call.

Upvotes: 2

Victor
Victor

Reputation: 4721

You mean like this:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["nameofconnection"].ConnectionString
SqlCommand cmd = new SqlCommand("test", con);

Upvotes: 0

Brandon
Brandon

Reputation: 70052

Use the ConfigurationManager class.

ConfigurationManager.ConnectionStrings["YourConnectionStringName"];

Upvotes: 2

Adrian Serafin
Adrian Serafin

Reputation: 7725

Look at ConfigurationManager class, you can access connection strings from there

Upvotes: 0

Related Questions