Access control from other form

  • Thread starter Thread starter HKSHK
  • Start date Start date
H

HKSHK

Hello all,

I have this problem:

I have 2 forms. Form1 contains a checkbox, which I want to uncheck
from Form2.
I set the checkbox to be "public static" and when I try to change a
property (e.g. Form1.checkBox1.Text="Sample") I get this error:
An unhandled exception of type 'System.NullReferenceException'
occurred in WindowsApplication2.exe

Additional information: Object reference not set to an instance of an
object.

If I set the checkbox to "public" only, it is not accessible from
Form2.

What do I have do change?

Thanks in advance.

Kind Regards,

HKSHK
 
HKSHK, you are getting this error because Form2 is a class, not an object.
Classes only become objects when they are instantiated using the "new"
keyword. Do you create "Form2" from Form1? If so, declare a variable like
this:

public class Form1
{
private Form2 form2 = new Form2();

Now you have acccess to Form2 from Form1. (Note you also should Show() form2
at some point, this code simply creates a copy of Form2 and does not show it
on the screen.)
Using this method, you'll be able to do this from Form1:

form2.checkBox1.Text = "Sample";

Also unmark "static" for checkBox and simply declare it as public. Static
members remain the same for every copy of the form you create. I don't think
that's what you want. When you practice C# and using the .NET framework a
bit more, I also suggest moving away from this method and simply
communicating with Form2 and have Form2 actually manipulate its own controls
rather than having them be manipulated from other forms. I find this way a
little harder to learn at first, but a much better design.
 
Back
Top