Search code examples
c#winformsmemo

Accessing form members from another class


The point is to notify the user using the memo when a packet is received/sent in a TCP Client. The old code was extra dumb,I used a Timer that used to add text in the memo since the Timer has access to the form members,lol.

The old code:

//Memo.Text += txt + "\n";

I played with it today,this is what I've done

In Form1's class

public string TextValue
{
    get
    {
        return Memo.Text;
    }

    set
    {
        this.Memo.Text += value + "\n";
    }
}    

I call the code like that:

Form1 myForm = new Form1();
myForm.TextValue = "test asdasd";

The memo modifiers are private,but that's not the problem.

The problem is that no text is displayed on the memo when i call the code.


Solution

  • By typing this:

    Form1 myForm = new Form1();
    

    you create a new instance of your form (Form1), but instead I guess you should use existing instance which most likely has been initialized already.

    One of the ways to do it:

    var form = Form.ActiveForm as Form1;
    
    if (form != null)
    {
         form.TextValue = "test asdasd";
    }
    

    Though this is not very good design. Try to use custom events instead.