Leo Zhang
Leo Zhang

Reputation: 55

How to access buttons in other class from Form1.cs

I have 9 buttons in Form1.Designer.cs and I want to access them in another class, Puzzle.cs because later on I need to modify button changes in model class. The code below is what I attempted.

private Button[,] buttons = new Button[3, 3]
{ { Form1.button1, Form1.button2, Form1.button3 }, 
  { Form1.button4, Form1.button5, Form1.button6 }, 
  { Form1.button7, Form1.button8, Form1.button9 } };

It fails as the modifier for buttons is not static. I changed them into static type but this causes errors for buttons. Can anyone give some advice?

Upvotes: 0

Views: 2286

Answers (2)

cwharris
cwharris

Reputation: 18125

To get things compiling correctly, you'll need to make the following changes:

public partial class Puzzle : Form
{
    private Button[,] buttons;

    public Puzzle(Form1 form1)
    {
        buttons = new Button[,]
        {
            { form1.Button1, form1.Button2, form1.Button3, },
            { form1.Button4, form1.Button5, form1.Button6, },
            { form1.Button7, form1.Button8, form1.Button9, },
        }
    };
}

The idea here is that Form1 is a class, not an instance of a class... A class is like a blueprint of a house, and a house is like an instance of that blueprint.

To get furniture out of the house, you first must instantiate and initialize that house (build, if you will), and then access the house's furniture instances.

In this case, you'll need to instantiate a new Form1, and pass that to the Puzzle form's constructor.

Form1 myForm = new Form1();
Puzzle myPuzzle = new Puzzle(myForm);

Puzzle will now be able to access that instance of Form1's buttons.

Note:

You can find the Program's instance of Form1 by looking in the Program.cs file of your solution.

Upvotes: 0

svick
svick

Reputation: 244787

You need a reference to an instance of the Form1 class. If it were called form, you could then access the button like form.button1.

But I'm not sure accessing buttons of the form from another class is a good design.

Upvotes: 2

Related Questions