C# : How to make connection avilable to all forms & classes in an Application?

  • Thread starter Thread starter RD
  • Start date Start date
R

RD

My application contains several Classes & Forms .
From the Login form I will get the User ID and Password for the
SqlConnection.
I established the connection through another class and I can get it in the
Login form.

In another form , say Employee form , I want to save the Employee details
to the Employee table. But when I tried to use connection which is already
opened I couldn't get it.

Then I tried to make the User Id and Password available to all classes and
forms in the project.
That way I can close and reopen it whereever I want in the application.
Anyway I am not able
to do it.

Please help me.

Thanks
RD
 
Hi RD,
To make a connection available in a all application, you must declare it
static in class. Perhaps, the
best solution is to use a Singleton pattern.
The code should look like this:

public class ConnectionSingleton
{
private static _connection = new SqlConnection();

public static CurrentConnection
{
get { return _connection; }
}
}

Anyway, this solution doesn´t work in a multithread application where all
trheads share this connection because some concurrency problem can arise.

I hope this can help you
Pablo Cibraro.
 
RD,

You can also create another constructor for the second form that
accepts ref objects from the first form (including that whole form if
you like!)... Don't forget to use this() to call the default
constructor when you use this method. Instantiate the form2 and pass
over whatever objects you like as reference parameters. Within the
second form just assign the ref objects to an internal variable and
use it throughout your new form...

private Form1 MyParentForm;

ie. in the new form create a second constructor

public Form2 (ref OleDbConnection oleConn, ref Form1
myMainForm):this()
{
...do more work with the connection, et. al.;
this.MyParentForm = myMainForm;
}

If I were you I would get all of my data into datasets and then
just pass the dataset over to the new form...
 
Back
Top