views:

36

answers:

1

I have used Anchor property for some of my controls at design time. but when I change the .Top property of those controls at run time, it seems that it is messing with the Anchor property and does not honor it anymore. what is happening? how to fix?

+2  A: 

I tried to reproduce the problem you describe, but was not able to match it exactly. The following example, however, may help you resolve the issue I suspect you are having.

(My employer blocks i.imgur.com, the image host for SO. If you have any problems viewing the screenshots, let me know.)

The following simple form contains a group box anchored on all four sides to its parent form.

Screenshot 01

When the button is clicked, the following code executes:

groupBox1.Top = 0;

Which results in the group box relocated like so:

Screenshot 02

Note, however, that anchoring is still honored:

Screenshot 03

I suspect you are looking for the effect that nothing except the top location of the control changes when you resize the control. Unfortunately, in this case, setting the Top property relocates the control rather than resize it.

You can accomplish resizing using the SetBounds() method, however. In the example below, I resize the anchored control, with a new top, using its existing bounds. Note that I don't take any measures to avoid illegal negative heights, which you probably should.

        int newtop = 0; // the new top bound
groupBox1.SetBounds(
        groupBox1.Left,
        newtop,
        groupBox1.Width,
        groupBox1.Height + groupBox1.Top - newtop);

This results in a resized and relocated control that continues to honor its anchoring afterward:

Screenshot 04

kbrimington