Search code examples
c#winformspanelpicturebox

Wrong position of picturebox when turned visible in a scrollable panel


CONTEXT :

I'm developping a windows form c# app with visual studio 2017.

The app has a scrollable panel (AutoScroll = true) filled with buttons.

Each button is associated to a picturebox.

They both are overlapping and have the same size and are sharing the same Tag attribute.

The tags are: 0 for the btn0 and picBox0, 1 for the btn1 and picBox1, etc...

When a button is clicked, its Visible attribute is set to false and the corresponding picBox's Visible attribute is set to true.

MY QUESTION :

When the picBox's visibility is set to true, it doesn't spawn/appear at the position it's placed in the designer of the form...

It looks like it doesn't spawn at a relative place in the parent panel...

Here's pictures to help yall understand my problem:

BEFORE: enter image description here

AFTER: enter image description here

You can barely see the borders of the picBox5, but they are there! (Zoom in! haha)

Before you ask:

YES, the picBox has the good Tag (5)

The position is fine in the designer and is not changed when the app is runing.

I looked with the debugger and the position seems fine...

I'm wondering if the picBox takes its position from the parent form instead of the parent scrollable panel?

How do I make the picture box spawn at the appropriate position?


Solution

  • All I had to do was reset the location of the target picBox taking in consideration the position of the scrollbar:

    picBox.Location = new System.Drawing.Point(picBox.Location.X + panel.AutoScrollPosition.X, picBox.Location.Y + panel.AutoScrollPosition.Y);
    picBox.Visible = true;
    

    You also need to make sure that the change of visibility is AFTER the relocation.

    This visibility change makes the scrollbar change its position and it makes the relocation wrong.