PDA

Click to See Complete Forum and Search --> : Acessing a class


DanDanDan1
Jan 7th, 2007, 01:25 PM
Hi everyone, I've been programming in VB 6 for some years now and decided it was time to move with the times. So I chose to go with c# .Net which seems to be the one I really want to progress with. It really is different though, anyway here my problem.

I have a class with some methods in, I create the class in form1 and everything is hunky dory but now I want to access these methods from form2 without recreating the class,

How do I access it??


Please explain in detail as I am very new to the world of c#

moeur
Jan 7th, 2007, 05:18 PM
when you say you created a class in form 1 do you mean that you created an instance of the class?

If so you can access in from form 2 if it is public in form 1 i.epublic myClass Form1Class = new myClass();Then in form2Form1.Form1Class.DoSomething();

DanDanDan1
Jan 7th, 2007, 05:32 PM
public myClass Form1Class = new myClass();

This line does not allow me to put public before it.

jmcilhinney
Jan 7th, 2007, 06:15 PM
This what OOP is all about. If you want to access that object then you need a reference to it. If the object is created in Form1 then Form1 will need to pass a reference to the object when it creates Form2. How do you pass data from one object to another? You do it all the time. You either set a property or pass a parameter to a method, which may be a constructor. You need to declare a property or method in Form2 that takes an object of that type, then you need to pass a reference to your object to that property or method from Form1 to Form2. Here are three examples, using a property, a method and a constructor:Form2 f2 = new Form2();

f2.SomeProperty = someObject;Form2 f2 = new Form2();

f2.SetSomeField(someObject);Form2 f2 = new Form2(someObject);

DanDanDan1
Jan 8th, 2007, 07:32 AM
So to clarify, If I put my class Class1 where you have someObject below I will then be able to put in form2...

Class1.sendInfo();

and it will call that method using the instance that was created in Form1

The reason I'm asking instead of just trying it is cos I'm at work and cant get near c# atm.

Form2 f2 = new Form2(someObject);[/QUOTE]


---------------------------------------------------------------

I really can't get my head around this it seems it should be really simple but I just can't make sense of it.

Thanks for everyones help.