Question

I have developed an application, based on 7 winform. My database is on MS Access. I want to create one common single class for connection string, and to use it in all winforms. So that, i can avoid copying and pasting connection string in all forms. I have no idea how to do it.

Was it helpful?

Solution

You can have your connection string in App.Config file

   <connectionStrings>
      <add name="MyDBConnection" providerName="System.Data.SqlClient"
            connectionString="Data Source=localhost;Initial Catalog=YourDB; Integrated Security=true" />
   </connectionStrings> 

And then you can access it like:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;

See: How to: Add an Application Configuration File to a C# Project

OTHER TIPS

I usually use a class and a static member like @scottk, but I'll wrap a check for the DEBUG preprocessor symbol so I can switch to a development database on debug builds. I also use OleDbConnectionStringBuilder for readability, even though it really is overkill:

public static class ConnectionStrings
{
    #if DEBUG
    public static string DBName
    {
        get
        {
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder
            {
                DataSource = @"C:\devDB.mdb",
                Provider = "Microsoft.Jet.Oledb.4.0"
            };

            return builder.ToString();
        }
    }
    #else
    public static string DBName
    {
        get
        {
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder
            {
                DataSource = @"C:\prodDB.mdb",
                Provider = "Microsoft.Jet.Oledb.4.0"
            };

            return builder.ToString();
        }
    }
    #endif
}

You can make a class with a static member and property.

public class Utils
{
    private static string connectionString = "Data Source=localhost;Initial Catalog=YourDB; Integrated Security=true";

    public static string ConnectionString
    {
        get
        {
            return connectionString;
        }
        set
        {
            connectionString = value;
        }
    }
}

Then you can access it like:

string connString = Utils.ConnectionString;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top