Oliver Robinson Oliver Robinson - 5 months ago 30
C# Question

How to make click button to change label text in other form?

How do I make it so when I click a button in Form1 (main form), it will open Form2 while also changing a label's text (Label4) as well.

My current code for the button:

Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.Show();


I don't want to change the showing code for the form I just want to add it so when I clicked the button to open that form it will also change the text on the label in Form2.

Answer Source

You use the object heirarchy to change the label directly.

Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.lblLabelToChange.Text = "Your Test Here";  //<= this line.
objFrmAdmin.Show();

If the label doesn't appear in intellisense, then you probably need to make it public. An alternative is to use the constructor, and pass the new test:

//Constructor for Admin form
public Admin(string newLabelText)
{
    this.lblLabelToChange.Text = newLabelText;
}

Call it via:

Admin objFrmAdmin = new Admin("The new text");