WinForms ListView, Remembering Scrolled Location on Reload

djdd87 picture djdd87 · Mar 9, 2009 · Viewed 10.9k times · Source

I've got a list view that I'm populating with 8 columns of user data. The user has the option to enable auto refreshing, which causes the ListView to be cleared and repopulated with the latest data from the database.

The problem is that when the items are cleared and repopulated, the visible area jumps back to the top of the list. So if I'm looking at item 1000 of 2000, it's very inconvenient to get back to that item.

Basically, what I'm asking is, how do I get the current scroll distances (x and y) and then restore them?

Answer

TheAgent picture TheAgent · Jan 24, 2010

I just wanted to provide some information for those who desperately try to use the buggy ListView.TopItem property:

  1. You MUST set the TopItem property AFTER calling ListView.EndUpdate
  2. The items of the ListView control MUST have their Text property set to something other than String.Empty, or the property won't work.
  3. Setting the ListView.TopItem throws null reference exceptions intermittently. Always keep this line of code inside a Try...Catch block.

Of course, this will cause the ListView's scrollbar to jump to 0 and back to the location of the top item, which is annoying. Please update this question if you find a workaround to this problem.