Chukzz Chukzz - 9 months ago 55
C# Question

Auto adjust buttons inside panel when one button is removed during runtime

I am having some buttons in a panel. I would like the buttons to be like the windows taskbar when one app is unpinned the space automatically get adjusted.

Currently in my panel when the user removes a button(b2) there remains a blank space between b1 and b3. I want b3 to take the blank space up.

Answer Source

Since you're in WinForms:

Make it a FlowLayoutPanel with the FlowDirection property set to LeftToRightand it will be handled automatically. If you're absolutely married to a standard Panel (I'm not sure why you would be), you'd have to reinvent the wheel a little bit:

public Form1()
    this.panel1.ControlRemoved += this.Panel1_ControlRemoved;

private void Panel1_ControlRemoved(object sender, ControlEventArgs e)
    int padding = 3;
    int lastRight = 0;

    foreach ( Control child in this.panel1.Controls ) 
        child.Left = padding + lastRight;
        lastRight = child.Right + padding;

This doesn't handle when controls are added etc... Use a FlowLayoutPanel.