winforms - C# Using Multiple Forms -
i have application has 2 forms. when click button on form 2 want able change text in form1:
public partial class form2 : form { public form2() { initializecomponent(); } private void button1_click(object sender, eventargs e) { form1.label1.text = "fred"; } }
the compiler throws error
how do this?
you confusing forms , form instances. form class. when form1 displays, what's displaying instance of form1 class. when form2 displays, instance of form2 displaying.
you're trying use
form1.label1.text = "fred";
but can set field or member of instance. you're referring class "form1".
you need 2 things. i'll assume form2 launched button on form1. add constructor form2 accepts instance of form1:
private form1 _starter; public form2(form1 starter) : this() { _starter = starter; }
then add property form1 exposes label text: not directly expose controls - given form should know controls on it:
public string labeltext { {return label1.text;} set {label1.text = value;} }
then have form2 set property:
private void button1_click(object sender, eventargs e) { _starter.labeltext = "fred"; }
Comments
Post a Comment