I’m adding buttons to a panel in a loop from AppSettings keys, but why it isn’t adding a little spaces between them?
foreach (var key in System.Configuration.ConfigurationSettings.AppSettings)
{
x = 4;
y = panel1.Controls.Count * 30;
Button button = new Button();
button.Text = key.ToString();
button.Visible = true;
button.Location = new Point(x+3, y+10);
button.Height = 45;
button.Width = 308;
button.TextAlign = ContentAlignment.MiddleLeft;
button.Show();
panel1.Controls.Add(button);
}
How it is look now:
And what I want:
>Solution :
Take a look at how the following values change for the three iterations of your loop:
| panel1.Controls.Count | y | button.Location.y (y + 10) |
|---|---|---|
| 0 | 0 | 10 |
| 1 | 30 | 40 |
| 2 | 60 | 70 |
Since the height of each button is 45, but you’re only increasing y by 30, the buttons are overlapping by 15.
To get rid of the overlap and add the space in between buttons that you want, you need to increase the value of y by (button height + padding amount) on each loop iteration. For example, with a button height of 45 and desired padding of 10, you’d want to increment by 55:
y = panel1.Controls.Count * 55;
You could also achieve the same effect by decreasing the height of the button:
button.Height = 25;
As mentioned by @user18387401 in a comment, you could also explore using other controls that will handle this sort of layout for you so that you don’t have to perform these calculations manually.

