How to fill Panel with Buttons of the equal size

c#, winforms

Solution

You can rely on `SizeChanged` event of the panel to get what you want. Sample code:

 private void Form1_Load(object sender, EventArgs e)
 {
     panel1.Dock = DockStyle.Fill;
     panel1.SizeChanged += panel1_SizeChanged;

 }

 private void panel1_SizeChanged(object sender, EventArgs e)
 {
     resizeButtons();
 }

 private void resizeButtons()
 {
     int totButtons = panel1.Controls.OfType<Button>().Count();

     Point curPos = new Point(0, 0);
     foreach(Button but in panel1.Controls.OfType<Button>())
     {
         but.Width = panel1.Width / totButtons; 
         but.Location = curPos;
         curPos = new Point(curPos.X + but.Width, 0);
     }
 }

This code makes sure that any number of buttons fill all the horizontal space no matter how much the size of `Panel1` changes.

Problem

I have a `Panel`, inside the `Panel` are two or more(in the future) buttons. How to make those buttons fully fill the `Panel` and have the same size independently of the `Panel` size changes during the application run? EDIT: According to answers which talk about resize event. The problem is that when the next button is added it won't automatically resize rest of the buttons. Also, as far as I understand this resizing would happen ONLY when the `Panel` is resized and first I have to carefully set the size of the buttons in the Designer. The ideal solution would work like Java's `GridLayout` -> no worries about the size of any button.

Original source