C# main class access

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do you access properties of the main program's class from another form? There does not apear to be an instance variable that can be used.
 
Hi Ray,

Ray Stevens said:
How do you access properties of the main program's class from another
form? There does not apear to be an instance variable that can be used.

A) Pass a reference to your main form when creating others.
B) Implement an public application singleton, containing the base logic -
which
may include a Collection of all the created forms - then you can access
the
singleton's collection of forms whenever you feel like doing form2form
communication ;-)
 
That means the functions that are opening the new forms are static methods
of the main form instead of instance methods. Is this on purpose, and, if
so, is there a reason they need to be this way?

Regardless, here's a pretty simple way of doing this. In you main form,
create a public static variable and use it for the call to
Application.Run(), e.g.

class MainForm : System.Windows.Forms.Form
{
public static MainForm TheMainForm = null;

public static void Main()
{
TheMainForm = new MainForm();
Application.Run(TheMainForm);
}
}

Now in any other form, if you need to reference the main form, do this:

class SomeOtherForm : System.Windows.Forms.Form
{
public SomeMethod()
{
string s = MainForm.TheMainForm.GetValueOfSomeTextBox();
}
}


Ken

Ray Stevens said:
Passing a reference to the main form does not work. The compiler give an
error "can't reference 'this'". I still can not find the instance variable
for the main form.
 
Hi Ken,

To answer your question: I don't know other than that is what VS.NET 2003 produced.

What you showed me worked. Thank you.

Ray Stevens
 
Back
Top