1

I'm creating a windows form that will programatically add a panel to another panel. I'm trying to customize the various properties of the new panel, such as color, and size, which works. However when I try to modify the margin, nothing works. I cannot find the Thickness struct either, since it's not a WPF app, it's a Windows Forms Application. Here is my code:

    private void buttonAddExercise_Click(object sender, EventArgs e)
    {
        Panel panel = new Panel();
        panel.BackColor = Color.White;
        panel.Size = new Size(200, 300);

        panel.Margin = new Padding(20);


        listOfExercisePanels.Add(panel);
        panelNewWorkout.Controls.Add(panel);
    }
M. Mar
  • 137
  • 2
  • 13
  • Possible Duplicate https://stackoverflow.com/questions/1003772/setting-margin-properties-in-code – Mac Man Oct 02 '17 at 10:50
  • i tried that article and didnt work, as i said, i cant find the thickness object – M. Mar Oct 02 '17 at 10:55
  • What do you mean by not being able to find the thickness object? You create a [Thickness](https://msdn.microsoft.com/en-us/library/system.windows.thickness.aspx) object (actually a struct) with the appropriate settings & then assign that to the Margin as shown in the link. – PaulF Oct 02 '17 at 11:02
  • Possible duplicate of [Setting Margin Properties in code](https://stackoverflow.com/questions/1003772/setting-margin-properties-in-code) – PaulF Oct 02 '17 at 11:04
  • When I type `Thickness`, it's underlined with red... – M. Mar Oct 02 '17 at 11:14
  • I found out that `Thickness` exists in WPF Apps, but not in Windows Forms Application. I dont know what to do. – M. Mar Oct 02 '17 at 11:20
  • @MacMan That's not a duplicate, the linked question is about WPF, but this one is on WinForms. Answer to both are completely unrelated. – Alejandro Oct 02 '17 at 13:01
  • As you found out, Thickness is in WPF. Here's your solution: https://stackoverflow.com/questions/19163809/set-panel-border-thickness-in-c-sharp-winform – Renato Afonso Oct 02 '17 at 15:12

2 Answers2

0

Firstly

To use Thickness you need to create/change your project .NET framework platform version to .NET Framework 4.5. because this method available only in version 4.5

Secondly

You must add DockStyle to Fill for Child components as:

Panel panel = new Panel();
        panel.BackColor = Color.White;
        panel.Size = new Size(200, 200);

        Label lb = new Label() { Text = "Hello" };

        panel.Padding = new Padding(10);
        lb.Dock = System.Windows.Forms.DockStyle.Fill;

        panel.Controls.Add(lb);

        this.Controls.Add(panel);

Thirdly

If you want to change Margin of the panel, you can put it into another parent panel

Emin Hasanov
  • 1,299
  • 1
  • 13
  • 29
-1

Add a reference to "PresentationFramework.dll",

and a using statement for:

using System.Windows;

PresentationFramework is not included as a reference by default.

MichaelLake
  • 1,735
  • 14
  • 17