Donotalo
Donotalo

Reputation: 13025

Properly placing user controls on FlowLayoutPanel

I'm working in a WinForms C# .NET 3.5 desktop software.

I'm trying to add a UserControl consists only a GroupBox in a FlowLayoutPanel. When I try the following code:

GroupBox gb = new GroupBox();

flowLayoutPanelConfig.Controls.Add(gb);
flowLayoutPanelConfig.SetFlowBreak(gb, true);

the GroupBox is shown beautifully:

enter image description here

But when I try to put the GroupBox in a UserControl:

GroupBox gb = new GroupBox();
UserControl uc = new UserControl();
uc.Controls.Add(gb);

flowLayoutPanelConfig.Controls.Add(uc);
flowLayoutPanelConfig.SetFlowBreak(uc, true);

and try to show the UserControl, the GroupBox breaks:

enter image description here

Why is that?

This is a test code. I've a user control in some separate files which I need to add in a FlowLayoutPanel. That also breaks this way.

How to resolve this?

Upvotes: 1

Views: 433

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205549

Probably a more realistic example is needed. It really depends on whether the UserControl is predesigned, hence has a correct size set in the design time, in which case it will show correctly. The problem in the runtime example you've shown is that the user control has default size which is different from the group box size, hence is clipping the child group box.

If you want to avoid the clipping and use the group box size, you should set UserControl.AutoSize property to true and UserControl.AutoSizeMode to AutoSizeMode.GrowAndShrink:

GroupBox gb = new GroupBox();
UserControl uc = new UserControl();
uc.AutoSize = true;
uc.AutoSizeMode = AutoSizeMode.GrowAndShrink;
uc.Controls.Add(gb);

flowLayoutPanelConfig.Controls.Add(uc);
flowLayoutPanelConfig.SetFlowBreak(uc, true);

Upvotes: 2

Related Questions