C# winform: Accessing public properties from other forms & difference between static and public properties

前端 未结 5 701
说谎
说谎 2020-12-03 18:54

I am trying to understand whats the difference between a static and public properties. But when I tried to access my public property \'Test\' in other form it says \'null\'.

5条回答
  •  -上瘾入骨i
    2020-12-03 19:23

    The first instance of Form1 shows an instance of Form2, and then Form2 creates another instance of Form1. This could work, but you set _test in the Form.Load event, which:

    Occurs before a form is displayed for the first time.

    You do not show the instance of Form1 you're trying to read Test from, so its Load event will not occur and Test remains null.

    You could add a constructor overload or property to pass the Form1 reference as @JohnKoerner mentions, but I would prefer to only pass the required variable, perhaps even encapsulated in an event, to reduce coupling. Form2 usually doesn't need to know all about Form1.

提交回复
热议问题