C# : global connection

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

RD

I opened a connection to the database in the login form.
Now in another form I tried to insert values to a table.
But the connection is not available in the form.

How can I make the connection global to all forms?
Where I can declare global variables?( Like in VB standard module)

Thanks
RD
 
One of the simplest ways to create a global connection is to create a
class with a static connection, and initialize it when your application
starts:

public class Data
{
public static SqlConnection Connection;
}

Somewhere in startup, you'd have Data.Connection = new
SqlConnection("...");

Then you could access it from wherever you need in your project. Using
a connection in this method has some caveats: you need to be careful to open
the connection and close it in an atomic fashion. You don't want two
seperate classes trying to use the connection at the same time, unless you
are very careful to always check the state, but that can quickly become too
complicated. So, if you are going to use a global connection, just be
careful about how you design around it!

Erik
 
Scott Allen said:
Add a public static property or method to a class in your project.
You might want to take a look at this paper about the singleton
pattern:

http://msdn.microsoft.com/practices/type/patterns/enterprise/impsingletonincsharp/

Unfortunately, that article is inaccurate. It claims that Double-
Checked Locking is thread-safe in .NET, when it isn't according to
Chris Brumme (who I trust rather more than the author).

See http://www.pobox.com/~skeet/csharp/singleton.html for more options.
 
Back
Top