Access an object on one form from another?

  • Thread starter Thread starter JamesB
  • Start date Start date
J

JamesB

Hello,
I have a (hopefully simple) problem.

I have a form, lets call it frmMain, and this has a database connection
object on it (sqlconnection) declared as public. All works well.

One of the operations I want to do will occur on a second form (call it
frmChild).

I can open up this quite happily with

frmChild NewChildForm = new frmChild();
frmChild.showdialog();

but on the child form I want to do a Database operation. frmMain.dbconn
(name of my connection) doesn't work, and from what I have read this is
because I need an object reference to frmMain rather than just frmMain. I
get that, but how do I reference something that already exists rather than
creating a new one?
Hope that makes sense

James.
 
JamesB said:
Hello,
I have a (hopefully simple) problem.

I have a form, lets call it frmMain, and this has a database connection
object on it (sqlconnection) declared as public. All works well.

One of the operations I want to do will occur on a second form (call it
frmChild).

I can open up this quite happily with

frmChild NewChildForm = new frmChild();
frmChild.showdialog();

but on the child form I want to do a Database operation. frmMain.dbconn
(name of my connection) doesn't work, and from what I have read this is
because I need an object reference to frmMain rather than just frmMain. I
get that, but how do I reference something that already exists rather than
creating a new one?
Hope that makes sense

James.


Actually - I think I worked it out?

Added a property to frmChild:

public frmMain MyParentForm;

then in the code in frmMain that opens the child I added:

frmChild.MyParentForm = this;

I can then see MyParentForm.DBConn from frmChild...
not run it yet, but is this the correct method to use?
James.
 
sure you does. It will work perfect.
acturally, you can use the following code:

in frmMain replace
frmChild NewChildForm = new frmChild();
frmChild.showdialog();
with:
frmChild NewChildForm = new frmChild();
NewChildForm.Owner = this;
frmChild.showdialog();
and in formChild when you would use frmMain,insert the following code:
frmMain fm = this.Owner as frmMain;
and now ,fm is a reference of frmMain
 

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

Back
Top