referenceing a class in a another .cs file

L

Larry Hilley

I have a form1 that creates form2. I also have a class A in a third .cs
file.
I do a new in form1 that creates A.
How do I reference A (and its data) form2.

All the examples I see only use only one .cs file, and only one form.

Thanks! Larry Hilley
 
A

Aravind C

Hi Larry,

You can pass the instance of class A from Form1 to Form2 either
through Form2's constructor or through a public method/property
in Form2.
Form2 can then stash away the instance of Class A in a field
that it can use to later access A's properties/methods.

For example, when Form1 creates Form2, it would do something like:

public void CreateForm()
{
A obj = new A();
Form2 myChildForm = new Form2(obj);
myChildForm.ShowDialog(this);
}

(or)

public void CreateForm()
{
A obj = new A();
Form2 myChildForm = new Form2();
myChildForm.MyData = obj;
myChildForm.ShowDialog(this);
}


Regards,
Aravind C
 
J

Jon Skeet [C# MVP]

Larry Hilley said:
I have a form1 that creates form2. I also have a class A in a third .cs
file.
I do a new in form1 that creates A.
How do I reference A (and its data) form2.

All the examples I see only use only one .cs file, and only one form.

The number of .cs files is irrelevant. Forms are just classes like any
other - so do what you'd do elsewhere: make sure that class A has a
reference to the second form, possibly passing it in the constructor to
A.
 

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