Reputation: 33
I have implemented a flowlayoutpanel to show images as kind of lightbox. I need to add new images into the FLP not at the end, but as leading images. For this, I created a List with the new Images and into this list I added the images of the FLP before the add operation. Then I cleared the Controls of the FLP and added all images from the temporary list. This all works fine, except that I would like to keep the scrollposition of the first image. I would like to know, how to scroll a control to the top of the panel. With ScrollControlIntoView the image becomes visible, but it is not scrolled to the top of the panel.
Please find the next 2 images to describe the requirement clearer:
The first image shows the situation before a new row is added above. Then after adding new images above the marked image (red arrow) the 2nd image shows that the yellow new row should be scrolled up.
I would like to scroll the yellow marked row out of the window, so that the marked image stays at its position
Upvotes: 3
Views: 4118
Reputation: 941257
The FlowLayoutPanel.AutoScrollPosition is crucial to get this right. It determines how far the panel is scrolled and by how much the Location property of its controls was adjusted to implement the scroll.
So first thing you want to do is obtain the control's Location property and adjust it by subtracting AutoScrollPosition to recover its original design location. Then you probably want to subtract the control's Margin. Then you know the new AutoScrollPosition to get it to the top. Assuming it can be scrolled to the top, wouldn't typically work for the control on the bottom for example, not otherwise something you have to verify.
Thus:
private void ScrollPanelTo(int index) {
var ctl = flowLayoutPanel1.Controls[index];
var loc = ctl.Location - new Size(flowLayoutPanel1.AutoScrollPosition);
loc -= new Size(ctl.Margin.Left, ctl.Margin.Top);
flowLayoutPanel1.AutoScrollPosition = loc;
ctl.Focus();
}
Tested with:
int index;
private void button9_Click(object sender, EventArgs e) {
ScrollPanelTo(index);
index = (index + 1) % flowLayoutPanel1.Controls.Count;
}
Upvotes: 6
Reputation: 3959
To change the position, try this code:
int currentPosition = FLP.Controls.GetChildIndex(controlToMove);
FLP.Controls.SetChildIndex(controlToMove, currentPosition - 1);
Or simply call BrintToFront()
method of the control you want to move to the top.
Upvotes: 2