Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

object

forms

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!

like image 488
Ivan Prodanov Avatar asked Apr 04 '09 13:04

Ivan Prodanov


4 Answers

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

like image 66
Konstantin Tarkus Avatar answered Nov 07 '22 19:11

Konstantin Tarkus


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.

like image 43
John Saunders Avatar answered Nov 07 '22 19:11

John Saunders


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.

like image 1
Aaron Daniels Avatar answered Nov 07 '22 18:11

Aaron Daniels


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);
like image 6
user2091150 Avatar answered Nov 07 '22 17:11

user2091150