Adding Panels to a Form in C# during execution
Solution 1
You can add panels to a form at runtime the same way the designer does - construct the Panel, and add it to the form (via this.Controls.Add(thePanel);
).
The easiest way to see the appropriate code is to add a panel to the form using the designer, then open up the "YourForm.designer.cs" file. The designer just generates the required code for you - but you can see the exact code required to duplicate what the designer would create.
As for the layout, I'd recommend watching the Layout Techniques for Windows Forms Developers video. It may give you some good clues as to the various options available for layout. There is nothing exactly like Java's GridLayout, though there are some open source projects that attempt to duplicate this functionality.
Solution 2
You definitely are gong to need to create a form application to get this to work. In addition, every control you see in the designer, can be added programmatically.
You could have a method that cranks out new panels as needed....
Here is the code that will create a new panel:
Panel panel1 = new Panel();
Once it is declared, you can access all the properties.
To add the panel to the form you would do something like this....
myform.controls.add(panel1);
So knowing that, you can create a method that will format your panel and return or add it tor the form....
Solution 3
You'll want to use TableLayoutPanel
or something along those lines. Then you can use the Controls
property to add panels to it.
bionicOnion
Updated on November 20, 2020Comments
-
bionicOnion over 3 years
I've been diving into C# for the first time by trying to recreate a screensaver that I made in Java comprised of a grid of panels which change color randomly. So far, I've gotten the code for the panels to work, and now I'm trying to add them to a Form to prototype the layout. I plan to determine the number of panels to be displayed at runtime (so that 16:9, 4:3, 16:10, etc. can all make the screensaver look good), but the only ways that I've found from searching the internet to add elements to a Form involve using Visual Studio's design tools. Therefore, I have a few questions:
How can I set up the layout of the Form in something akin to Java's GridLayout?
What's the code needed to add elements to a Form?
Is there a better thing for me to be using instead of a Form?
-
John Saunders about 12 yearsI presume you're talking about Windows Forms, but if you were to tell us, then I wouldn't need to presume.
-
bionicOnion about 12 yearsYes, Windows Forms. Sorry about any confusion.
-