How to access form objects from another cs file in C#

前端 未结 5 672
广开言路
广开言路 2020-12-29 15:15

In the form.cs file I have two buttons,a memo and a timer.My question is: How do I access the timer or the memo from another cs file?

I\'ve tried to make the objects

5条回答
  •  时光取名叫无心
    2020-12-29 15:37

    Select your button in designer, go to it's properties and change "Modifiers" property from Private to Public.

    Then you can get access to it from another class, something like this:

    public static class Test
    {
        public static void DisalbeMyButton()
        {
            var form = Form.ActiveForm as Form1;
    
            if (form != null)
            {
                form.MyButton.Enabled = false;
            }
        }
    }
    

    Note: it's just an example and definitely not a pattern for good design :-)

提交回复
热议问题