[ACCEPTED]-How to access form objects from another cs file in C#-object

Accepted answer
Score: 16

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

Then you can get 4 access to it from another class, something 3 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 2 definitely not a pattern for good design 1 :-)

Score: 6

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

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

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

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

Score: 6

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

Application.Run(new Form1());


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

declare it 1 like

public static Form1 formInstance;

and use

Score: 1

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

For example, this is how you 3 would do it:

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

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

string theButtonTextIAmLookingFor = Form1.MyButton.Text;

Just something you might want to check.

Score: 0

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


More Related questions