I am trying to change the Label1.Text
on my Form1
(owner) by Button1_Click
triggered from Form2
, but there are no changes on Label1.Text
. It is still empty string (""). I have double/triple checked my code. I could not find anything wrong.
Here's what I have done so far:
Form1
// Label1 is inside the TabControl Page 0
// Label1.Modifier property already set to public
// and Label1.Text = ""
public static FrmOwner Self;
public FrmOwner()
{
InitializeComponent();
Self = this;
}
private void Button2_Click()
{
FrmForm2 frm = new FrmForm2 ();
frm.ShowDialog();
}
Form2
public FrmForm2()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
FrmOwner.Self.Label1.Text = "Changed Text";
}
I am sure there's something wrong with my code, definitely. Please help.
CodePudding user response:
You can pass Form1 instance to Form2. Then access From1 public methods and properties from From2.
Form1
public static FrmOwner Self;
public FrmOwner()
{
InitializeComponent();
Self = this;
}
private void Button2_Click()
{
FrmForm2 frm = new FrmForm2 (this);
frm.ShowDialog();
}
public void SetLabel(string txt)
{
Label1.Text = txt
}
Form2
private FrmForm1 _frm1;
public FrmForm2(FrmForm1 frm1)
{
_frm1 = frm1;
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
_frm1.SetLabel("New Text");
}