Click here to Skip to main content
15,564,017 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a form (Report). In public partial class Form1 I have:-
public Report report;

In Form1_Load I have:-
Report report = new Report();

In button1_Click I have:-
report.Show();
This shows no error until run, when it gives the error "Object reference not set to an instance of an object."
I need to make updates to the form Report from several methods.

What I have tried:

Read everything I can google on passing data between forms, working with multiple forms.
Many Questions Answered at Once — Collaboration between Windows Forms or WPF Windows[^]
appears to be authoritative but I am not advanced enough to understand it fully.
Posted
Updated 6-Mar-22 18:47pm
v2

1 solution

The thing you're not understanding is "scope". Since you defined the report variable in the Form1_Load method, it is only visible in that method. You also don't need the "public Report report;" line either.

Move the line that defines the report variable to the Button1_Click method and the error goes away.
C#
Report report = new Report();
report.Show();
 
Share this answer
 
Comments
ormonds 7-Mar-22 2:32am    
Thank you. However I also have a number of other methods, each of which needs to update textBox1.text on form report.
Is it possible to make the form and its controls global?
Dave Kreskowiak 7-Mar-22 7:39am    
Then you can keep the "private Report report = new Report();" at the class level. You still do not need the line in Form_Load and remove the line from Button1_Click.

That will make the report variable visible to al methods in your form class.
ormonds 7-Mar-22 7:50am    
Thank you. Now I get it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900