Main form instance name

  • Thread starter Thread starter Bill D
  • Start date Start date
B

Bill D

In a simple Windows forms application, the main form is
called Form1. Within this form's class, I refer to the
the running instance of this main class as "this" as in
this.Text = "NEW TEXT"

I want to do something like change this Text on the Form1
window from within another class. Trying
Form1.Text = "TEXT FROM CLASS"
or
Form1.ActiveForm.Text = "TEXT FROM CLASS"
lead to errors such as "object reference not set to an
instance of an object". This makes sence because Form1 is
the class name and not the instance name. However, what
is the instance name, the name of the instance that is
referred to as "this" within the main class?

Thanks for any input.
 
You ar eright, your problem is that you are trying to access Form1 which is
the actual class and not the object. The default Main() creates an
annonymous object of Form1. Therefore, you dont actually have a handle on
the form.
I would suggest that you pass a handle to your form in your classes'
constructor (ie: public classConstructor(Form1 handleToForm1) and save it as
a local variable of type Form1. That way, any public variables would be
accessible. Or safer yet, if you know your only going to change the Text
value, just send a handle to that variable.

hope this helps

Marco
 
In your 2nd for (or class), you will need to create a field to hold a
reference to your Form1 object.

One way to do this is to create a property in the 2nd class and then have
Form1 assign itself to that property.

In 2nd class, do something like this:

private Form1 mainForm;
public Form1 MainForm
{
get{return mainForm;}
set{mainForm = value;}
}

In your Form1 class (maybe in the ctor), do something like this:
secondClass.MainForm = this;

Then in your 2nd class you can access all the public properties of Form1
thru the private mainForm field (now a member of your 2nd class).

In order to make it even cleaner, I would probably make one or both of these
classes singletons.
Going one step further, the design issue to consider is that you probably
don't want your 2nd class to have to know much or anything about Form1. I'm
just guessing, because you didn't say what your second class was. But the
problem with the above suggestion is that you don't really want both classes
to be dependent on each other and one way you can fix this is with
singletons, but I'm probably getting too far from your original question
with that discussion.

HTH
Mountain
 
Back
Top