I have a System.Windows.Forms.Panel
with some content.
I am trying to programmatically scroll the panel (vertically) either up or down.
I have tried setting the AutoScrollPosition
property to a new Point
on the panel but that doesn't seem to do it.
I have the AutoScroll
property set to true.
I even tried to set the VerticalScroll.Value
twice as suggested here, but that doesn't seem to work either.
This is what I am currently doing:
//I have tried passing both positive and negative values.
panel.AutoScrollPosition = new Point(5, 10);
The X and Y values on AutoScrollPosition remain 0 and 0.
Any help or direction on this would be greatly appreciated it.
Thanks in advance,
Marwan
Try this:- panel.ScrollControlIntoView(childcontrol);
This should work. childcontrol is the particular control that you want to show in your display area.
If you have a class that derives from
Panel
, then call these two protected methods to scroll the panel:In my example,
item.BoundingRect.Bottom
is the Y coordinate of the bottom of a thumbnail, and I need to scroll the panel down so that the whole thumbnail is visible.@King King's solution of creating a temporary Control just so that scrolling could be done seemed "heavy" to me. And @Hans Passant's suggestion of setting
AutoScrollMinSize
andAutoScrollPosition
didn't work for me.Leave
AutoScroll
to its default value of 'true'.I had an issue where I couldnt get my panel to scroll back to top . I tried many things to try and get the panel to scroll back to the top after populating it with many controls.
Nomatter what I did it always put the VScroll bar to the bottom.
After exhaustive testing I found it was because my controls had the TabStop property set to true (default on user controls) was causing the issue.
Setting TabStop to false fixed it.
Use @King King Answered Code and if you want to hide horizontal and vertical scroll bar, just apply the below code in the constructor or initialization.
This surprisingly works! NOTE THE MINUS SIGN in the code. There is strange behavior in setting scroll position. If you set the position to exact value (50), it goes negative when you read it next time (-50). So you have to invert it before setting new scroll value.
Scroll down:
Scroll up similarly, (-current.Y - 10)
Here is a solution. I guess you can scroll your
Panel
by arbitrary position usingWin32
however there is a simple trick to help you achieve your requirement here:Or use extension method for convenience:
UPDATE
If you want to set the exact position, modifying the code above a little can help:
Another solution you may want to use is using
Panel.VerticalScroll.Value
. However I think you need more research to make it work as you expect. Because I can see once changing theValue
, the scrollbar position and control position don't sync well. Notice thatPanel.VerticalScroll.Value
should be betweenPanel.VerticalScroll.Minimum
andPanel.VerticalScroll.Maximum
.