Lecture – How To – Read Connection String from Web Config

Read Connection String from Web Config

Prerequisites

Knowledge of C#. This uses Visual Studio and SQL Server.

Summary

I create a connection string stored in the web.config and demonstrate how to access it with the .NET objects in code. Terminology and classes used for this are covered in this example.

Video 

Reference Materials

The DatabaseHelper

namespace MyNewWebsite
{
    public class DatabaseHelper
    {
        public static string connectionString()
        {
            System.Configuration.Configuration rootWeb = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyNewWebsite");
            System.Configuration.ConnectionStringSettings connstr;
            if (rootWeb.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                connstr = rootWeb.ConnectionStrings.ConnectionStrings["TraumaDataConnectionString"];
                return connstr.ConnectionString;
            }
            return String.Empty;
        }
    }
} 
namespace MyNewWebsite
{
    public partial class DatabaseConnection : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Text = DatabaseHelper.connectionString();
        }
    }
} 

Additional Information

Other lectures that cover the topic of connection strings

ADONET Object Model – Creating a Database Connection

Creating-a-Database-Connection-String

COP 4834 Lectures Page