.net – How to you stop a Winforms Panel from scrolling

netpanelwinforms

If you put a DataGridView that is 400 pixels high on a panel that's 300 pixels high, so that there's a scroll bar on the panel, then scroll down so that the lower half of the grid is shown, then click on a control outside the panel, then click on a line in the grid, the panel scrolls up to the top and the wrong row in the grid is selected.

It's not just a DataGridView; it happens with any control that's higher than the panel, eg Infragistics UltraWinGrid, Rich Text Box. I raised it as a bug with Infragistics, but they say it's a Microsoft issue.

I've tried using all the relevant events for the controls, but the Panel scroll happens before the events fire.

Any suggestions?

Best Answer

This is caused by the ScrollToControl event being fired automatically by the ScrollableControl class, and the event handler scrolling to show the top left of the control that got focus. This behavior is not helpful when the scrollable container control only contains one control. I was very frustrated by this behavior until I found out how to stop it.

The way to stop this behavior is to override the ScrollToControl event handler, like this:

class PanelNoScrollOnFocus : Panel
{
    protected override System.Drawing.Point ScrollToControl(Control activeControl)
    {
        return DisplayRectangle.Location;
    }
}

Replace your panel control with this panel control. Done.