简体   繁体   中英

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

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 public,but it didn't work,please give me a source or a project,so I can see where I'm mistaken.

Thanks!

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 :-)

There is Form object already instanced in Program.cs, except it have no reference. With simple editing you can turn

Application.Run(new Form1());

to

Application.Run(formInstance = new Form1());

declare it like

public static Form1 formInstance;

and use

Program.formInstance.MyFunction(params);

I worry whenever I hear someone talking about "another .cs file" or "another .vb file". It often (though not always) indicates a lack of understanding of programming, at least of OO programming. What's in the files? One class? Two?

You're not trying to access these things from another file , you're trying to access them from a method of a class, or possibly of a module in VB.

The answer to your question will depend on the nature of the class and method from which you're trying to access these things, and the reason why you want to access them.

Once you edit your question to include this information, the answers you receive will probably show you that you shouldn't be accessing these private pieces of the form in classes other than the form class itself.

Although I agree with John Saunders, one thing you may be doing wrong, assuming that you have everything accessible through public modifiers, is that you don't have the instance of that form.

For example, this is how you would do it:

Form1 myForm = new Form1;
string theButtonTextIAmLookingFor = myForm.MyButton.Text;

I am assuming that you may be trying to access it like it's static, like this:

string theButtonTextIAmLookingFor = Form1.MyButton.Text;

Just something you might want to check.

The intuitive option is simply to make the control field public Here is a very good solution to solve this issue..

http://searchwindevelopment.techtarget.com/answer/In-C-how-can-I-change-the-properties-of-controls-on-another-form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM