C # in form 2 does not show string in label

0

I do not understand why but Form 2 does not show the label text in form 1.

form 1

    private void button1_Click(object sender, EventArgs e)
    {
        string Username = textBox1.Text;
        HelloForm HF = new HelloForm();
        HF.Show();
        HF.Username = Username;
        this.Hide();
    }
}

form 2

    public string Username { get; internal set; }

    private void HelloForm_Load(object sender, EventArgs e)
    {

        label1.Text = "Hello " + Username;
    }
}
    
asked by anonymous 25.07.2016 / 15:53

1 answer

1

You need to allow label1 to be changed by another class. In this case you should change the Modifiers property.

In your case it is not working because the property does not have the value at the time you use it. If you debug, you will see that at the moment, Username has the null value. In this case I indicate you create an overload in the class constructor.

public HelloForm(string _username)
{
    InitializeComponent();
    Username = _username;
}

and then you can simplify the button by using the new constructor.

private void button1_Click(object sender, EventArgs e)
{
    HelloForm HF = new HelloForm(textBox1.Text);
    HF.Show();
    this.Hide();
}

I took the test here and it worked the way you need it.

    
25.07.2016 / 16:10