-->

Cannot remove spacing between controls in TableLay

2019-02-28 12:09发布

问题:

There's some spacing between the Buttons I add to my TableLayoutPanel. I removed the border in the Button and set the Margin and Padding to 0 in the Panel. But I continue getting that spacing.

tableLayoutPanel.RowCount is set to 8 and the Rows collection I've added 8 rows with Size Type Absolute.

Am I missing something? Here's the code:

    private void FillSelectLayout()
    {
        tableLayoutPanelSelect.Controls.Clear();
        tableLayoutPanelSelect.RowStyles.Clear();

        tableLayoutPanelSelect.RowCount = 8;

        for (int i = 0; i < 8; i++)
        {
            Button buttonSelector = new Button();
            buttonSelector.Height = 64;
            buttonSelector.Width = 100;
            buttonSelector.FlatStyle = FlatStyle.Flat;
            buttonSelector.FlatAppearance.BorderSize = 0;
            buttonSelector.BackColor = Color.Yellow;
            tableLayoutPanelSelect.Controls.Add(buttonSelector, 0, i);
        }
    }

Here's how it's displayed:

回答1:

To remove the space between buttons in cells, it's enough to set dock property of them to fill and then remove default margins of buttons:

var b = new Button();
b.Dock = DockStyle.Fill;
b.Margin = new Padding(0);

Note:

  • Usually it's better to set Dock property of controls which you host in cells to Fill. This way your controls will follow TableLayouPanel sizing rules which you set for columns and rows.

  • TableLayoutPanel use Marging property of control to set the location of control in cell. So If you don'n want to set Dock and you prefer to set the Size manually, it's enough to set the Margin only.



回答2:

I .. set the Margin and Padding to 0 in the Panel.

Why didn't you remove the Margin in the Buttons instead:

buttonSelector.Margin = new Padding(0);

MSDN:

The Margin property defines the space around the control that keeps other controls a specified distance from the control's borders.



回答3:

I faced the same problem while using different control in TableLayoutPanel

You can do this

  1. Go to Design View
  2. Click on the properties
  3. GoTo Columns, When you click text box besides Columns, a button (...) appears on extreme right, click it
  4. A pop up window appears, Select AutoSize (Instead of Absolute or Percentage).
  5. In the same window in Show: select Rows and again select Autosize.
  6. Click okay and you are done.