Access Form controls from static class [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-02 10:50:52

You can declare in the static form:

private static MyformType myform;

public static void setmyform(MyformType myform1)
{
  myform=myform1;
}

although, that concept generally isn't so good, maybe better way would be passing your form as argument to functions called in the static class, and make your contorl which should be accesed public, by chanign acces modifier in propertis box of the form

public static void EgClearText(Textbox tb)
{
  tb.Text="";
}
public static void DoSomethingElseWithTheForm(MyformType myform)
{
  myform.someOtherContol.Visible=false;
}

You can apply singleton pattern to your form. Note that Instance will return reference to last created instance of MyForm, so you shouldn't have more than one instance of MyForm out there.

Backing field:

    private static MyForm _instance

Singleton accessor:

    public static MyForm Instance
    {
        get
        {
            return _instance;
        }
    }

Once you beging using the class, you can assign its reference to the backing field

    public MyForm()
    {
        _instance = this;
    }

As a side note; if you have a choice of technologies, check out WPF. It has bindings to programmatically get and set values of UI controls at

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