Programmatically assigning Margin and/or Padding to a Label

B. Clay Shannon picture B. Clay Shannon · Apr 30, 2012 · Viewed 31.6k times · Source

In trying to get some labels in a TableLayoutPanel to move from the top left of their cells to the center of the cells, I'm trying to experiment with adding padding and/or margins.

However, nothing I've tried works. Here's the code I've tried and the results:

// Setting the padding just cuts off the bottom part of the text
//lbl.Padding = new System.Windows.Forms.Padding(1);

// How to set Margin?
//lbl.Margin = new System.Windows.Forms.Margin(1); <- This mimics "Padding" but is not recognized
//lbl.Margin = new Thickness(6); <- This is the only example I could find, but it's for WPF

Answer

ispiro picture ispiro · Apr 30, 2012

Try:

lbl.Margin = new Padding(1);

You might also want to do:

lbl.Dock = DockStyle.Fill;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.AutoSize = false;