Configuration files and ConnectionStrings

.NET, C# Add comments

One of the first things I’ve learned as .NET developer was using of App.config or Web.config files. Almost every application in which development I took a part had some database. Here is the brief sample how to connect to SQL Server from C#:

			string connString = @"Server=(LOCAL);Database=Northwind;User ID=sa;Password=;";
			string sqlString =  "SELECT * FROM PRODUCTS";
			DataSet ds = new DataSet();
			SqlConnection conn = new SqlConnection(connString);
			conn.Open();
			SqlDataAdapter da = new SqlDataAdapter(sqlString, conn);

			da.Fill(ds);
			dgrProducts.DataSource = ds;
			dgrProducts.DataBind();
			conn.Close();

This code will open connection to database, read table and fill data set. Then we bind data from data set to dataGrid or GridView (control named dgrProducts).
But it is not a good practice to keep connection string hard coded. Place it into configuration file.

< ?xml version="1.0" encoding="utf-8" ?>

	
	
		
	

and here is how you can read value from configuration file. It is a good practice to create new project, type of Class Library for that.

using System;
using System.Configuration;

namespace ConnectionString
{
	public class Configuration
	{
		public static string ReadConnectionString
		{
			get
			{
				return ConfigurationSettings.AppSettings.Get("ConnectionString");
			}
		}
	}
}

this sample runs on .NET 1.1 framework
For 3.0 .NET we use:

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace ConnectionString
{
    public class Configuration
    {
        protected static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ConnectionString"].
                    ToString();
            }
        }
    }
}

As you can see we use System.Configuration reference.

Leave a Reply

You must be logged in to post a comment.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in