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:

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)
   {
      // 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.
/// 
/// The main entry point for the application.
/// 
[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);
}


Last modified by Mohit @ 4/13/2025 8:19:23 PM