Click here to Skip to main content
15,921,210 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
I have many forms in my project, all forms retrive data one form (main) by :
C#
main frm = new main();

then use all resource from form(main).
just one form, give me the following error(Error 1 A field initializer cannot reference the non-static field, method, or property );
the error appear here:
private TreeNode<PictureNode> root = new TreeNode<PictureNode>(new PictureNode(frm.DataGridView3.Rows[0].Cells[1].Value.ToString(), Image.FromFile(id + ".jpg")));


at   frm

how i can fix this problem.
thank you

What I have tried:

i suppose that it is the scope, but i can not solve it.
Posted
Updated 9-Jan-17 4:02am
Comments
[no name] 9-Jan-17 9:26am    
Try initializing your field from the constructor.

You cannot use an instance variable to initialize another instance variable - because the order in which such initializations is not fixed, or even defined.

If you want to do that, do it as part of the class constructor instead of as a field initializer - that way you control the order and can guarantee that all fields are correctly initialized before they are used.

[edit]typos[/edit]
 
Share this answer
 
v2
1. If the frm variable is not a member variable, and the TreeNode call is in a separate method, then yes it is the scope. frm will have to be a member variable initialized at construction of the object.

2. With the above statement being fixed (if applicable), does the class use a public property DataGridView3 or is this the actual data grid view control? If the latter, and you did not change the access modifier to public (or protected if this class is an extension), then you will get another error. If this occurs you should read up on encapsulation and make the proper changes to be able to access that controls properties.

Encapsulation links:

Tutorials Point
C# Station
CSharp Lectures
 
Share this answer
 
Instead of using a Form to hold shared data, use a static global class.
 
Share this answer
 

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