I want to change a label text from my function class in the main form. I think I was able to narrow down the problem, but I can't find a good solution. Maybe I misunderstood the instances in WinForms.
Favorite solution Form 1
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1 (can the problem be that i put my functions in a class and not a winform?)
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = txt;
}
But that didn't work and I don't understand why. Doesn't that call the currently displayed instance of Form1?
Solution that works Form 1
public static Form1 f1Instance;
public Label lbl;
public Form1()
{
InitializeComponent();
f1Instance = this;
lbl = label1; //label1 = made by designer
}
Class 1
public void changeLblTxt(string txt)
{
Form1.f1Instance.lbl.Text = "Hello";
Form1.f1Instance.Show();
}
But I use it to call Form1 multiple times, don't I? That wouldn't go well with a longer runtime and more interactions, would it?
I have found countless articles on this subject but none have been able to help. Does anyone know of an article that shows a good solution?
CodePudding user response:
If you have a class that interacts with the form, then that class should have a reference to the form instance. Using static fields and lists to try and get the "current" form instance seems like a poor design.
I would just hand the class the form instance:
class Class1 {
private Form1 form1;
public Class1(Form1 form1) {
this.form1 = form1;
}
// other stuff
}
Form1 frm = new Form1();
Class1 cls1 = new Class1(frm);
cls1.changeLblTxt("Test");
And similarly if you have two forms:
class Form2: Form {
private Form1 form1;
public Form2(Form1 form1) {
this.form1 = form1;
}
// other stuff
}
Form1 frm1 = new Form1();
Form2 frm2 = new Form2(frm1);
fmr2.someMethod("Test");
CodePudding user response:
After chatting with chatgpt i found a way: Form1
public static List<Form1> formList = new List<Form1>();
public FormSettings()
{
InitializeComponent();
formList.Add(this);
}
Form2
public void someMethod()
{
Form1 f1 = Form1.formList[0];
fs.SetLabelText(lines[i]);
}
Can someone explain to me why the list works but assigning it directly (first try to solve it) didn't work? As far as I know, I did the same thing.