Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# add spaces between buttons in a loop

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And what I want:

enter image description here

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading