Accessing form members from another class

帅比萌擦擦* 提交于 2019-11-30 21:25:08

问题


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.


回答1:


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.




回答2:


Maybe you should consider publishing an event in your tcpclient. Then your form will be able to listen to this event and display proper information.




回答3:


Assuming Memo inherits from Control and assuming you set it with the proper modifier, the problem you may be going through is that you're likely trying to set the text from a worker thread (the one that's used to run the TCP client). If that's the case, then you need to check the InvokeRequired field of your control and if true invoke a delegate that will set the text for you. Below is a short and easy C# snippet.

private void SetTextOnMemo(string txt){
    if(Memo.InvokeRequired){
        Memo.Invoke(SetTextOnMemo, txt);
    }
    else{
        Memo.Text = txt;
    }
}


来源:https://stackoverflow.com/questions/717264/accessing-form-members-from-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!