Search code examples
c#winformsgroupbox

Groupbox adjust width based on text length


I have a c# app (winform) that generates Groupboxes from an xml file and based on what's in the file, populates it with Radio Buttons or CheckBoxes. Each of these groupboxes have a name, some of them are longer and they get cut off half way through.

enter image description here

This is how they are generated.

int nc = groupNodes.Count;
for (int i = 0; i < nc; i++)
  {
       node = groupNodes[i];
       GroupBox box = new GroupBox();
       box.AutoSize = true;
       box.AutoSizeMode = AutoSizeMode.GrowAndShrink;
       box.Text = node.Attributes["name"].Value;
       //......
}

I tried using the following,

Size textSize = TextRenderer.MeasureText(box.Text,box.Font);
box.Width = (int)textSize.Width;

and tried the following

box.width = (int)box.text.length;

but none of this made any difference.

I also came across This thread. But since I don't use the PaintEventArgs I'm not sure how this applies to me.


Solution

  • Setting the groupbox width is only one of your problems.

    It probably should be done like this:

    groupBox.AutoSize = true;
    int oWidth = groupBox1.Width;
    int tWidth = (int)groupBox.CreateGraphics().
                                MeasureString(groupBox.Text, groupBox.Font).Width;
    
    if (tWidth > oWidth)
    {
        groupBox.AutoSize = false;
        groupBox.Width = tWidth;
    }
    

    Note:

    • This code make use of the AutoSize property. Which will make the GB wide enough to hold its content ie. the RadioButtons&CheckBoxes with their texts. Therefore these should be set before adjusting the GB sizes.
    • The result will have AutoSize true for some GB and false for others..
    • After changing the width of the GBs they will need to be repositioned unless they sit in a FlowLayoutPanel!
    • Their contents (The RadioButtons etc ought to still sit correctly as you placed them before). You did Add them to the GBs, right? If some don't show, post the code you create them with!

    So the order is this:

    1. Create GBs with their Text
    2. Add contents with their Texts
    3. Resize GBs
    4. Reposition GBs (shouldn't be necessary with FLP)