Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms ListView, Remembering Scrolled Location on Reload

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?

like image 628
djdd87 Avatar asked Mar 09 '09 13:03

djdd87


2 Answers

Look at the ListView.TopItem property. It has an index, which should contain its position in the list. Find that index in the new list, and set TopItem to that item, and it should do the scrolling automatically.

like image 168
Chris Doggett Avatar answered Oct 18 '22 18:10

Chris Doggett


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.

like image 28
TheAgent Avatar answered Oct 18 '22 19:10

TheAgent