My windows form button is set to width 0 when it should be full width

Viewed 46

I'm working on a Excel add-in project that will require me to procedurally generate some controls in a windows task pane. While experimenting, I ran into an issue where this button keeps having its width set to 0, and I don't understand why.

If I don't use any anchoring or docking then the button shows up, but at its default width and height. I am trying to get it to span the width of the layout panel, and it was my understanding you could accomplish this by using AnchorStyles Left and Right, or with DockStyle Fill. However, as soon as I add these properties the width gets set to 0 (as seen from the debugger). I checked the width of the root control (this) and the button's parent control FlowLayoutPanel, and they are both the default non-zero size.

What am I doing wrong?

    public MyUserControl()
    {
        FlowPanel = new FlowLayoutPanel
        {
            Name = "My Flow Panel",
            TabIndex = 0,
            FlowDirection = FlowDirection.TopDown,
        };

        Button button1 = new Button
        {
            Name = "button1",
            Text = this.Width.ToString(),
            FlatStyle = FlatStyle.Flat,
            Padding = new Padding
            {
                Left = 10
            },
            Parent = FlowPanel,
            Anchor = (AnchorStyles.Left | AnchorStyles.Right)
        };

        FlowPanel.Controls.Add(button1);
        this.Controls.Add(FlowPanel);
    }
1 Answers

You can't anchor like that in FlowLayoutPanels. Instead, subscribe to the SizeChanged event and modify the button width there. You'll probably also need to set the width when you create the button, so below I've just created a method you can call from both places.

FlowPanel.SizeChanged += new System.EventHandler(this.FlowPanel_SizeChanged);

private void FlowPanel_SizeChanged(object sender, EventArgs e)
{
  SetButtonWidth();
}

void SetButtonWidth()
{
  button1.Width = FlowPanel.Width - FlowPanel.Padding.Horizontal - button1.Margin.Horizontal;
}
Related