Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access form component from another class

Tags:

c#

forms

class

I hope that the title and this simple example says everything.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void UpdateLabel(string str)
    {
        label1.Text = str;
       MessageBox.Show("Hello");
    }

    private void buttonIn_Click(object sender, EventArgs e)
    {
        UpdateLabel("inside");
    }

    private void buttonOut_Click(object sender, EventArgs e)
    {
        MyClass Outside = new MyClass();
        Outside.MyMethod();
    }
}

public class MyClass
{
    public void MyMethod()
    {
         Form1 MyForm1 = new Form1();
         MyForm1.UpdateLabel("outside");
    }
}

When I'm trying to change lable1 from MyClass it does nothing. But I can get to the UpdateLable method from outside, it says Hello to me, it just doesn't change the label.

like image 881
cozzy Avatar asked Dec 09 '22 07:12

cozzy


2 Answers

Use a delegate for setting your label

public class MyClass {
    Action<String> labelSetter;

    public MyClass(Action<String> labelSetter) {
        this.labelSetter = labelSetter;
    }

    public void MyMethod() {
        labelSetter("outside");
    }
}

.

public void buttonOut_Click(object sender, EventArgs e) {
    var outside = new MyClass(UpdateLabel);
    outside.MyMethod();
}
like image 103
Mark H Avatar answered Jan 02 '23 01:01

Mark H


a bit unsure because the example actually leaves some bits unclear... but here is a try:

public class MyClass
{
    public void MyMethod(Form1 F)
    {
         F.UpdateLabel("outside");
    }
}

this works as long as MyClass is NOT running on a different thread - otherwise the call to UpdataLabel must be synchronized with the UI thread...

EDIT:

private void buttonOut_Click(object sender, EventArgs e)
{
    MyClass Outside = new MyClass();
    Outside.MyMethod(this);
}
like image 27
Yahia Avatar answered Jan 02 '23 01:01

Yahia