Search content within the blog

Wednesday, April 22, 2009

Storing and retreiving connection string from web.config

<add name="pubs" connectionString="Data Source=yourservername; Initial Catalog=pubs;User ID=yourusername;Password=yourpassword;" providerName="System.Data.SqlClient"/>

Note if windows authentication use following format
<add name="Pubs" connectionString="Server=(local)\SQLExpress;Integrated Security=True;Database=pubs;Persist Security Info=True"
providerName="System.Data.SqlClient" />

/// <summary>

/// method to retrieve connection stringed in the web.config file

/// </summary>

/// <param name="str">Name of the connection</param>

/// <remarks>Need a reference to the System.Configuration Namespace</remarks>

/// <returns></returns>

public string GetConnectionString(string str)


//variable to hold our return value

string conn = string.Empty;

//check if a value was provided

if (!string.IsNullOrEmpty(str))


//name provided so search for that connection

conn = ConfigurationManager.ConnectionStrings[str].ConnectionString;



//name not provided, get the 'default' connection


conn = ConfigurationManager.ConnectionStrings["YourConnName"].ConnectionString;


//return the value

return conn;


No comments:

Post a Comment