Here’s a strange piece of behaviour – a puzzle (with a solution) for you.

Imagine that you’re working with Win.Forms, constructing a resizable layout using a TableLayoutForm as the host.

At Design time, your form looks like this:

Each label is configured as follows:

  • Anchors: Left (Left align, vertically centre)

  • Autosize: true

Each control is configured:

  • Anchors: Left Right (Stretch across cell, vertically centre)
  • Maximum Size: (240,0)

But, at run time it looks like this:

Notice how the controls are offset down from their proper location.

Why is this happening? Any ideas?

[Solution below]

Note that the top edge of each control is vertically centered within its cell – this is your clue.

Turns out that the TableLayoutPanel pays attention to the MaximumSize property of the controls – with the maximum size of these controls set to (240,0), the panel assumes that all the controls will be zero height and conveniently centered them vertically in their cells.

There are a number of possible fixes …

  • With the rows of the TableLayoutPanel set to AutoSize, we could set the Anchors of the controls to Left|Top|Right (Stretch across the top of the cell)

  • We could remove the MaximumSize property entirely by setting it to (0,0)

  • We could set the height of the MaximumSize property to the actual height of the control

I chose the later.

It’s an interesting example of how different features interact - if I had happened to set up these controls in any other way, the bug wouldn’t have surfaced.


blog comments powered by Disqus
Next Post
StyleCop for ReSharper  24 Feb 2009
Prior Post
Unit testing with LINQ  18 Feb 2009
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
February 2009