where shall i put my connection string

Moorzee

Well-known member
Joined
May 31, 2006
Messages
92
Location
England
Programming Experience
3-5
About to start teaching myself some asp.net. Where should I put my connection string?
 
Ok no-one replied so I trawled t'webnet thing and sussed out the web.config file. added two settings in there(LiveEnv and DevEnv database connection strings) and retreived using the system.web.configuration namespace. Just in case anyone struggles like mad like me here is how I have done it.:eek:

VB.NET:
[SIZE=2][SIZE=2][COLOR=#008000]' Set the root path of the Web application that contains the[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]' config file.[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] confPath [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] = [/SIZE][SIZE=2][COLOR=#800000]"/WebSite2"[/COLOR][/SIZE]
 
[SIZE=2][COLOR=#008000]' Instantiate a configuration object to access the config file.[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] config [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] Configuration = WebConfigurationManager.OpenWebConfiguration(confPath)[/SIZE]
 
[SIZE=2][COLOR=#008000]'Get all the connectionStrings settings from the file[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] connStrings [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] ConnectionStringsSection = config.GetSection([/SIZE][SIZE=2][COLOR=#800000]"connectionStrings"[/COLOR][/SIZE][SIZE=2])[/SIZE]
 
[SIZE=2][COLOR=#008000]'Create a single setting to access the setting you want to use[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] settings [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Configuration.ConnectionStringSettings[/SIZE]
 
[SIZE=2][COLOR=#008000]'Populate the setting from the collection using either index or the name[/COLOR][/SIZE]
[SIZE=2]settings = connStrings.ConnectionStrings([/SIZE][SIZE=2][COLOR=#800000]"DevEnv"[/COLOR][/SIZE][SIZE=2])[/SIZE]
 
[SIZE=2][COLOR=#008000]'Use the connection string of the setting for the connection object[/COLOR][/SIZE]
[SIZE=2]cxnLogin.ConnectionString = settings.ConnectionString[/SIZE]
 
[SIZE=2][COLOR=#008000]'Open connection[/COLOR][/SIZE]
[SIZE=2]cxnLogin.Open()[/SIZE]
[/SIZE]
 
The System.Configuration.ConfigurationManager class includes a ConnectionStrings property which exposes the connectionstring entries in the config file:
VB.NET:
cxnLogin.ConnectionString = _
 ConfigurationManager.ConnectionStrings("DevEnv").ConnectionString
 
Back
Top