Access form label from another class/namespace

2019-01-29 06:06发布

I know this has been asked thousands of time but still after a lot of research I can't find a solution and I am really sorry about this post.

I want to access my Label from a class in another namespace. This is a sample of code to understand better what I am trying to do:

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



//class in another namespace
class Servers
    {
        public void _SetlabelText()
        {
           Main.label1.Text = "New Text";
        }
    }

How am I supposed to do it the proper way?

1条回答
不美不萌又怎样
2楼-- · 2019-01-29 06:52

One option is to store a reference to the form in the constructor like this:

public class Servers
{
    private Form _frmMain;
    public Servers(Form frmMain)
    {
        _frmMain = frmMain;
    }
    public void SetlabelText()
    {
        _frmMain.label1.Text = "New Text";
    }
}

And use it like this:

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
        var servers = new Servers(this);
        servers.SetlabelText();
    }
}

However, it's typically advised to return back to the Form class and set it there, like this:

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
        label1.Text = Servers.GetTextForLabel();
    }
}
public class Servers
{
    public static string GetTextForLabel()
    {
       return "New Text"; //(I assume this will be much more complex)
    }
}
查看更多
登录 后发表回答