Pascali70,
I'm going to make a few assumptions:
a. You are using Visual Studio 2005.
b. You are developing a windows forms application.
You have many good options, but two that I frequently use, are as follows. NOTE that neither of these are acceptable for storing passwords.
1. When Visual Studio builds the framework for a Windows Forms application, it automatically builds a class called Program. Look for it in your solution explorer (Ctrl + Alt + L). If I'm not mistaken, the class is a static class (similar to a shared class in
VB, again if I remember correctly).
Add a global variable, or constant containing your connection string. For instance:
Code:
static class Program
{
//------------------------------
// Global Variables & Constants
//------------------------------
public const string DEFAULT_CONNECTION_STRING = @"Data Source=.\sqlexpress;Database=Northwind;Integrated Security=SSPI;";
//------------------------------
// Public Methods
//------------------------------
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
2. Another simple way to store and access a connection string is to store it as a resource. Again, look in your Solution Explorer (Ctrl + Alt + L), but this time, look for something called "Properties." Double click on it. The window that opens will have a number of tabs on the left side. Click on the "Resources" tab. This will display all the resources that the project is storing.
There are two buttons at the top left of the window. Drop down the first button and select "Strings." At this point, you will be looking at all the string resources stored with the project. You can enter a Name-Value pair, such as:
Code:
Name Value
----- --------------
MyConnectionString Data Source=.\sqlexpress; Database=Northwind; Integrated Security=SSPI;
Then you can access the connection strings from some other class within your application as is illustrated from the constructor of a class called Form1.
Code:
public partial class Form1 : Form
{
//------------------------------
// Member Variables
//------------------------------
protected string m_connectionString = "";
protected string m_otherConnectionString = "";
//------------------------------
// Constructors
//------------------------------
public Form1()
{
InitializeComponent();
m_connectionString = Program.DEFAULT_CONNECTION_STRING;
m_otherConnectionString = Properties.Resources.MyConnectionString;
}
}
Cheers.
- Roger Nedel