Sunday, June 19, 2016

ASP.NET Configurations: Retrieve Connection String Programmatically

So you have a connection string that you want to use in the Web.config file and you want to use in the code behind file.  You can do that with a single line of code in your .cs file.  Below are the steps to retrieve a connection string in the web.config file programmatically.

1. Make sure you have a connection string in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>


2. Now in the Default.aspx.cs file type in the following in the top of the file, where all the using statements are to use the System.Web.Configuration namespace
using System.Web.Configuration;
Obviously you can use it in any .cs file, the Default.aspx.cs is just an example.


3. In the Page_Load method type in the following line
    string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;
To display the connection string on your browser, type the following line
Response.Write(connectString);

No comments:

Post a Comment