Usage of global sqlconnection throughout my project

G

Guest

Hi all,

I have a question/problem concerning usage of my sqlconnection throughout my
program.
In my main form (frmMain) I defined an sqlconnection (I've set the
connection public so that I can open & close the connection from everywhere
in my app).
My main form is an mdi parent which contains several mdi-childs.
To open and close the sqlconnection in an mdi-child i use the following:

((frmMain)this.mdiparent).sqlconnection.open();
((frmMain)this.mdiparent).sqlconnection.close();

But this works for an mdi-child. Now I want to use this sqlconnection within
a form that I show as modal, let me explain this a bit further:
I have an mdi-child open, from there I want to open a small form (by
..ShowModal()) and in that form I must open and close the sqlconnection to
save my in that form edited data.

Can somebody help me how to address my sqlconnection from my frmMain in this
form that is showed modal?

Thank you for helping me out.
Kind regards,
Tom.
 
B

Bob Grommes

Offhand I think you'd have to pass a reference either to the connection or
to frmMain to the constructor of the modal form, or else send it to a public
property of the modal form before calling ShowDialog() on it.

For globally available stuff like this I tend to prefer using a class of
static members rather than relying on it being in a top level form. Then
it's just a matter of something like Globals.DBConnection.Open(),
Globals.DBConnection.Close(), etc. and it works the same no matter where you
call it from.

--Bob
 
P

Paul E Collins

Can somebody help me how to address my
sqlconnection from my frmMain in this form
that is showed modal?

Either pass the SqlConnection to the modal form's constructor, or
declare the SqlConnection as 'static' so that no instance of the
parent form is required.

P.
 
G

Guest

Thank you Bob & Paul for helping me out.

I will use and try both options.

Kind regards,
Tom.
 
U

Uri Dor

actually, .NET uses connection pooling, so all you need is to have the
same connection string in all the connection instances you want to share
and it'll use the same connection in its internals
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top