user3059947
user3059947

Reputation:

Control properties don't allow to be changed

My mainForm contains two buttons(btnLoad & btnChange) and a panel

When the btnLoad is clicked, it loads the other forms(there are 5 different froms with different controlers) into the panel. Let me assume one of it named Form2 which contains a label(labelMessage)

My problem is, when I click the btnChange the following statement won't work.

f2.labelMessage.Text = "Button Change Clicked";

My codes are

// codes on mainFrom

private void btnChange_Click(object sender, EventArgs e)
{

   Form2 f2 = new From2();
   f2.labelMessage.Text = "Button Change Clicked"; //labelMessage's modifier is public

}


private void btnLoad_Click(object sender, EventArgs e)
{
    panelDock.Controls.Clear();
    Form f2 = new Form2();
    f2.TopLevel = false;
    panelDock.Controls.Add(f2);
    f2.Show();

}

is this wrong?

Upvotes: 0

Views: 63

Answers (1)

user2509901
user2509901

Reputation:

Since Form2 is already shown you should use Application.OpenForms instead of creating a new instance of Form2

private void btnChange_Click(object sender, EventArgs e)
{
    Form2 f2 = (Form2)Application.OpenForms["Form2"];
    f2.labelMessage.Text = "Button Change Clicked"; //labelMessage's modifier is public
}

From your comment that Form2 is in a panel you can try

private void btnChange_Click(object sender, EventArgs e)
{
    Form2 f2 = (Form2)panel1.Controls["Form2"];
    f2.labelMessage.Text = "Button Change Clicked"; //labelMessage's modifier is public
}

Upvotes: 6

Related Questions