GroupBox autosize

Take a GroupBox , put the Label inside, and then set AutoSizeMode = GrowAndShrink and AutoSize = true .

There are two problems:

  • There is a huge gap between the Label and the bottom of the GroupBox (almost enough to fit another Label lol);
  • AutoSize does not GroupBox.Text property.

The question is how to make GroupBox.AutoSize workable ? Correctly means: the minimum width should be sufficient to match GroupBox.Text , for some unknown reason there should be no spaces (this is not Margin , nor Padding , and it looks pretty ugly).


I tried to measure the string length in OnPaint and set MinimumSize right there. It works, but I doubt it, as if I would like to install MinimumSize later - it will be lost after redrawing.


Refresh, here is a screenshot:

enter image description here

+5
c # winforms autosize groupbox
source share
3 answers

You can get rid of the unwanted yellow space below by deriving a new class from GroupBox, which will slightly change the bottom edge. In VB, something like ...

 Public Class BetterGroupBox Inherits GroupBox Public Overrides Function GetPreferredSize(ByVal proposedSize As Size) As Size Dim ns = MyBase.GetPreferredSize(proposedSize) Return New Size(ns.Width, ns.Height - 15) End Function End Class 
+2
source share

Just that the location of your Label fixed at some point other than (0,0) , try the following:

 label1.Location = Point.Empty; 

You can also try setting the Padding your GroupBox to 0 for everyone (default is 3):

 groupBox1.Padding = new Padding(0); 
+1
source share

It seems that the GroupBox control has a predefined sort GroupBox when growing the control if AutoSize = true . That is, when the control (inside the GroupBox) hits 20 pixels or so at the bottom of the GroupBox, the GroupBox starts to grow. This causes 20 pixels to fill from the bottom of the lowest control to the bottom of the GroupBox (highlighted in yellow by @Sinatr).

Based on my observations, padding seems to be less when growing Width for GroupBox.

Anyway, you can do something like the following โ€œwork aroundโ€ the problem:

  public void MyFunction() { groupBox1.AutoSize = true; // Do stuff (eg, add controls to GroupBox)... // Once all controls have been added to the GroupBox... groupBox1.AutoSize = false; // Add optional padding here if desired. groupBox1.Height = myBottomMostControl.Bottom; } 
0
source share

All Articles