Scrolling DataGridView per pixel

2020-04-29 14:27发布

问题:

I am making a .NET 4 WinForms application which reads data from a database and displays rows in a DGV. However the number of rows is larger than maximum number of rows that can fit on screen at once. To display all data, I need to scroll the DGV automatically until the last row and update the data source after that in order to refresh the DGV.

I found it's easy to do that by simply incrementing FirstDisplayedScrollingRowIndex by one. However the scrolling is too sharp. I would like it to scroll smoothly.

To do that, I have tried calling ScrollRows method directly. That method is not public so I had to use Reflection like this:

var scrollRows = dgv.GetType().GetMethod("ScrollRows", BindingFlags.Instance | BindingFlags.NonPublic);
scrollRows.Invoke(dgv, new object[] { 1, -1, ScrollEventType.SmallIncrement });

I call this code from a timer_Tick method which is triggered every 20 ms.

The DGV scrolls smoothly but it doesn't draw any row below those which were visible at the beginning.

Is there any way I can make it scroll smoothly AND display data properly?

回答1:

You need to add your DGV to Panel



回答2:

I have dropped the need for DGV and therefore for this kind of approach. I have created a FlowLayoutPanel with Panels created dynamically to display the required data, designed the way I wanted it to be.

There is probably a way to perform smooth scrolling of DataGridView which could be accomplished by analyzing .NET reflection of DataGridView code, but again, I found an acceptable alternative and I'm using it.

There is a way to accomplish smooth scrolling of DGV by actually placing it on a panel with a scrollbar. That way, scrolling a panel scrolls the DGV too. This way wasn't convenient for me because DGV headers would get scrolled out of screen and I needed them to be visible at all times.