-1

I got this error.I tried to create an instance of control but didn't work. Can somebody help me?

Error CS0120 An object reference is required for the non-static field, method, or property 'Control.Controls'

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static void Main(string[] args)
        {
            foreach (var button in Form1.Controls.OfType<Button>())
            {

            }
        }
    }
Darejk
  • 9
  • 4
  • 1
    What are you actually trying to do? – Sweeper Dec 29 '19 at 03:28
  • You're mixing code used in a Console application with code used in WinForms. You can find `static void Main()` in `Program.cs`, rarely used for UI-related operations. You should describe what you're actually trying to accomplish here. If you're trying to get/set properties of all the Buttons that are children of the current Form, the `OnLoad` method override (or a class method delegate) is a better choice. – Jimi Dec 29 '19 at 08:19
  • Well I'm trying to make the buttons' texts auto resize every time there is a change in the window form app. – Darejk Dec 29 '19 at 09:20
  • 1
    What does *make the buttons' texts auto resize* mean? Change the Font.Size (use a larger/smaller Font size)? What *change in the window form*? When a Form is resized? Have you tried anchoring the Buttons? It won't change the Font size, but it will resize the Buttons, no further coding required. Or add the Buttons to the cells of a TableLayoutPanel, setting the Buttons' Dock Property (e.g., `[Button].Dock = Fill`). – Jimi Dec 29 '19 at 09:50
  • I mean when the user click the rectangle button on the top to maximize or restore the window size, I really want the text in the box to change the size according to the window. Using TableLayoutPanel alone only changes the button but not the text inside... – Darejk Dec 31 '19 at 11:01

1 Answers1

6

First of all what is the purpose of static Main in Form1

also you need to change this line

var form1 = new From1();

foreach (var button in form1.Controls.OfType<Button>())

or if you want to access it inside Form1 class

foreach (var button in this.Controls.OfType<Button>())

anyway all above codes should be out of a static method.

Reza
  • 18,865
  • 13
  • 88
  • 163
  • Nice, the error disappears but the code doesn't work the way I wanted. I'm trying to make the buttons' texts auto resize every time there is a change in the window form app. This is my first time coding a winform app with c# so there are things that I can't understand lol. – Darejk Dec 29 '19 at 09:23
  • Didn't he answer your question? – Alexandru Lache Dec 29 '19 at 16:24