Automatic resizing of controls in group box

M

MB

Hi!

I am trying to make a dynamic GroupBox that will contain a variable
number of child controls of a single type, e.g. RadioButtons or
CheckBoxes. I want to read the neccesarry information about the
controls (such as the text) from an xml-file, create controls, and then
place them on top of another in the group box. The problem is how to
give the controls and the group box the correct size. The group box
(and its child controls) should have a set width, but the height should
resize based on the child controls. Also, I need the child controls to
adjust their height based on the Text property.


Any ideas on how to do this? What I need is some way of making e.g. a
RadioButton adjust it height (but have constant width) to fit the text
it displays. I have tried with the Label control, and have set the
AutoSize property to true, but it will only resize the width. I managed
to get the Label to adjust correctly by splitting the text in words,
adding word by word, and adding a "\n" when the PreferredWidth property
was larger than the width I wanted, and at the end reading the
PreferredHeight, but the RadioButton and CheckBox doesn't seem to have
this property. Any other suggestions?

MB
 
D

Dave

Get a Graphics object for the control that needs to be resized. (This is provided in the paint method, but you may need to access
it using CreateGraphics in the TextChanged event: (sender as Control).CreateGraphics())

The Graphics object has a method called MeasureString which can be used to obtain the height of the text that will be painted on the
control. Specify the text from the Text property of the control and a StringFormat instance that is appropriate.

Set the height of the control using the result from the MeasureString object.

FYI, in my experience it seems this is never a perfect result. Usually, I have to pad the result from MeasureString with a constant
number of pixels. If the font style changes, this "constant" value may need to change also. I think this occurs since Text is
rendered in a device-independant manner in the framework. Just pick a value that will suit most, if not all, font styles such as 5
px. The height may not be as tight as you want it, but it won't clip any text at the bottom.

Also, don't forget to account for the non-client area of the control. For instance, if you have a two pixel border around the
control add another four pixels to the height returned by MeasureString.

GL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top