0

I want to pass my Label I use in my mainForm to an anonymous form. By anonymous form I mean this form count can be infinite. I will show my code to make it clear.

This is my second form.

LABEL sourceObj;
public frmCounters(string text, ref LABEL _sourceObj)
{
   InitializeComponent();
   sourceObj = _sourceObj;
   this.Text = text;
   this.lblInfo.Text = text;
   this.lblTime = sourceObj;
}

and this is how I call it

AnonymForm afrm = new AnonymForm("TEST1", ref lblTEST1);
afrm.Show();

all I want to achieve here is update anonyform's label whenever I change the source from my main form. I have tried with and without ref keyword in constructor. I've bind the value I get in constructor to another variable I hold in anonymform. I also wanted to try send text property as reference but Visual Studio said I can't pass properties with ref keyword.

My question is how can I achieve that?

user229044
  • 232,980
  • 40
  • 330
  • 338
Shino Lex
  • 487
  • 6
  • 22

1 Answers1

3

Add to AnonymForm class method like:

public void SetLabelText(string value)
{
    this.label.Text = value;
}

And call it from main form:

afrm.SetLabelText("TEXT");
Backs
  • 24,430
  • 5
  • 58
  • 85
  • I don't hold afrm. I call it in my main menu strip. Maybe thats the problem? should I hold the afrm somewhere? – Shino Lex Dec 18 '19 at 11:08
  • 1
    @ShinoLex yes, you can hold it in some variable, or if you have many forms, hold them in array. – Backs Dec 18 '19 at 11:09
  • The amount of AnonymForm will be unknown. And not all AnonymForm's will have the same Label. Some of them may have lblTEST2 or lblTEST3 labels – Shino Lex Dec 18 '19 at 11:14
  • Nope, holding the form object in a list did not solve it. The changes I do in mainform.lblTEST1 does not reflect to my anonymForm – Shino Lex Dec 18 '19 at 11:16
  • @ShinoLex you shouldn't change lable on main form. Yoy must put label on child form and change text via method. – Backs Dec 18 '19 at 11:21
  • How can I do that? I'll be honest I did not understand your suggestion. – Shino Lex Dec 18 '19 at 11:47