Not logged in - Login

Sample Connection String Setup for a Windows Application

Create 3 projects in your solution: client project, BL project, & a DL project. Set references as follows:

  • DL project - no references
  • BL project - references the DL project
  • Client project - references the BL project. Note: the client project should NOT reference the DL project.

Create basic classes in the BL & DL projects.
In the DL project class, create methods & properties to hold the connection string.

public class dal
{
   public static string ConnectionString { get; set; }

   public dal()
   {
      if (string.IsNullOrWhiteSpace(dal.ConnectionString))
      {
         throw new System.Exception("Connection string not set in dal class");
      }
   }

   public SqlConnection GetConnection()
   {
      SqlConnection conn = null;

      // create the connection
      conn = new SqlConnection(dal.ConnectionString);

      // open the connection
      conn.Open();

      return conn;
   }
}

In the BL project, create a static method to send the connection string information to the DL class.

public class bl
{
   public static void SetConnectionString(string connectionString)
   {
      // do the contract validation here.
      System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(connectionString), "Parameter 'connectionString' cannot be blank");

      // save the connection string
      Database_Sample_DL.dal.ConnectionString = connectionString;
   }
}

In the main() function of the client project, send the connection string from the configuration to the BL class.

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   // send our connection info to the BL class
   Program.SetConnectionString();

   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Application.Run(new Form1());
}

private static void SetConnectionString()
{
   // get the connection string from our properties
   string connectString = Properties.Settings.Default.SampleConnection;

   // send our connection string to the BL class via a static method
   Database_Sample_BL.bl.SetConnectionString(connectString);
}