C # winform: accessing public properties from other forms and the difference between static and public properties

I am trying to understand what is the difference between static and public properties. But when I tried to access my public property “Test” in a different form, it says “null”.

Heres Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private string _test;

    public string Test
    {
        get { return _test; }
        set { _test = value; }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _test = "This is a test";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();
    }
}

Here is Form2:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Form1 frm1 = new Form1();
        label1.Text = frm1.Test;
    }
}

To check the value of “Test” in Form1, I put a breakpoint on this line:

label1.Text = frm1.Test;

But the value is null.

Please help me how can I access public properties in other forms.

And BTW I tried to make this public property "public." I can access this using this:

Form1.Test

, "Test" Form2, . , . - . !

EDIT: (For follow up question) 

, . , test "", , , Form2. :

public partial class Form2 : Form
{
    private Form1 f1;
    public Form2(Form1 ParentForm)
    {
        InitializeComponent();
        f1 = ParentForm;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = f1.Test;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        f1.Test = "This test has been changed!";

        this.Close();
    }
}

, Form2 , Form1_Load, "Test" , ! Form1 Form2 ? , . , !

+7
5

, Form1.

, - Form1 Form2.

public partial class Form2 : Form
{
    private Form1 f1;
    public Form2(Form1 ParentForm)
    {
        InitializeComponent();
        f1 = ParentForm;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = f1.Test;
    }
}

, Form2 Form1, :

Form2 frm2 = new Form2(this);

, , :

public string Test
{
    get { return _test; }
}
+6

"static"

=

public static Form1 frm1 = new Form1();
public static Form2 frm2 = new Form2();

Form1

Program.frm2.show();

Form2

label1.Text=Program.frm1.text; 
+1

frm1 . , Test ( Form1_Load).

0

Form1 Form2, Form2 Form1. , _test Form.Load , :

, .

Form1, Test, Load , Test null.

, Form1, @JohnKoerner, , , . Form2 Form1.

0

, .

, , . , , .

, , : . , . , , .

, . , . ( ). . :

Foo() {    Foo()   {       Bar = "fubar";   }

public static string Bar { get; set; }

}

Static classes are often used as services, you can use them like this:

MyStaticClass.ServiceMethod (...);

-1
source

All Articles