How to set the height of a WinForms CheckedListBox to fit to dynamic contents without scrollbars
I recently encountered a problem trying to get the Windows Forms CheckedListBox control to resize it’s height to exactly fit it’s contents (items) without showing scrollbars.
Initially I looked at using the obvious PreferredHeight property, but it quickly became evident that the preferred height didn’t give me a useable value. It was out by a few pixels over ten items and when I got up into hundreds of items it was way out.
I also had to contend with the fact that this code was going to be run across XP, Vista, Window 7/8 and potentially across multiple DPI settings (100%, 125%, 150%).
In the end the solution wasn’t too bad.
// Explicitly set height to fit options checkBoxCtrl.ClientSize = new Size(checkBoxCtrl.ClientSize.Width, checkBoxCtrl.GetItemRectangle(0).Height * checkBoxCtrl.Items.Count);
The key concepts here as:
- Set the ClientSize property rather than the Size property. ClientSize is just the internal area the items populate so you don’t have to worry about padding and border widths applied via VisualStyles
- All items in my list are the same height so I can just measure the height of the first item and multiply by the number of items in the list
- The GetItemRectangle property returns the height of an item in the list taking into account different DPI settings and the padding/margin between items in the list. Note: this is much simpler than trying the measure the graphic (checkbox glyph) or Text of an item and the padding/margin between items.