Reputation: 25
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.
Upvotes: 0
Views: 695
Reputation: 7095
Change Admin
form constructor, something like this:
//add parameter text
public Admin(string text)
{
InitializeComponent();
//change label 4 text
this.Label4.Text = text;
}
change the way you're initalizing Admin
form like this:
Admin objFrmAdmin = new Admin("text to show on label");
this.Hide();
objFrmAdmin.Show();
EDIT: another way to achieve that is to make public method on admin form and call it. So, leave constructor without parameter, like it was and make public method on your Admin
form, like this:
public void ChangeText(string text)
{
this.Label4.Text = text;
//put other code here if needed, ie. hide buttons or something like that
}
Now, just call that method after you initialized your Admin
form.
Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.ChangeText("text to show");
objFrmAdmin.Show();
Upvotes: 3
Reputation: 1048
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");
Upvotes: -1